我为“商品”类 View 制作了一个 ArrayAdapter 和数组列表,现在我想要它,以便每次我单击 + 按钮时,它都会增加我想要/单击的产品数量。我对 java 和 android Soz 非常陌生。
So I wanna add this
int quantity = 1;
/**
* This method displays the given quantity value on the screen.
*/
private void displayQuantity(int number) {
TextView quantityTextView = findViewById(R.id.quantity_text_view);
quantityTextView.setText(number);
}
/** this method is used to increase quantity*/
public void add (View view) {
quantity = quantity + 1;
Log.v("merch","Added +1");
displayQuantity(quantity);
}
对此:
public class merchandise extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid_view);
ArrayList<Merch> merchArrayList = new ArrayList<Merch>();
merchArrayList.add(new Merch(R.drawable.icon,"PRODUCT1"));
merchArrayList.add(new Merch(R.drawable.icon,"PRODUCT2"));
merchArrayList.add(new Merch(R.drawable.icon,"PRODUCT3"));
merchArrayList.add(new Merch(R.drawable.icon,"PRODUCT4"));
merchAdapter merchAdapter = new merchAdapter(this,merchArrayList);
GridView merchListView = (GridView) findViewById(R.id.merch_grid_view);
merchListView.setAdapter(merchAdapter);
}
我尝试过的事情: 1)创建了一个新类,并将其命名为“merch_buttons”,但我收到一条错误消息,说“该方法应该位于 View 的父上下文中”,我不明白这一点。 2)将其添加到创建时,但意识到不能将方法添加到方法中 3)在 on create 方法之后添加它,但它给出了一个错误,指出“java.lang.IllegalStateException:无法执行 android:onClick 的方法”。
4)尝试创建一个非常简单的新类和一个带有一个按钮和 TextView 的 xml,但在 3)处仍然出现错误......(也问了一个有关该问题的问题)。
太好了,该怎么办。
最佳答案
在onCreate()中setContentView之后初始化每个UI Widget;给你一个例子:
TextView quantityTextView = findViewById(R.id.quantity_text_view);
如果您想在全局范围内访问它,
public class merchandise extends AppCompatActivity {
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid_view);
textView = findViewById(R.id.quantity_text_view);
ArrayList<Merch> merchArrayList = new ArrayList<Merch>();
merchArrayList.add(new Merch(R.drawable.icon,"PRODUCT1"));
merchArrayList.add(new Merch(R.drawable.icon,"PRODUCT2"));
merchArrayList.add(new Merch(R.drawable.icon,"PRODUCT3"));
merchArrayList.add(new Merch(R.drawable.icon,"PRODUCT4"));
merchAdapter merchAdapter = new merchAdapter(this,merchArrayList);
GridView merchListView = (GridView) findViewById(R.id.merch_grid_view);
merchListView.setAdapter(merchAdapter);
}
其中包括您尝试使用 onClick 的按钮。
关于java - 如何使用 ArrayList 中的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60901059/