java - 如何在 ArrayList 中使用按钮
问题描述
我为“商品”视图制作了一个 ArrayAdapter 和 Array 列表,现在我想要它,这样每次我点击 + 按钮时,它都会增加我想要/点击的产品数量。我对 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”,但是我收到一条错误消息,说“该方法应该在视图的父上下文中”,我不明白这一点。2)将它添加到 on create 但意识到您不能将方法添加到方法 3)在 on create 方法之后添加它但它给出了一个错误,说“java.lang.IllegalStateException:无法为android执行方法:点击“。
4) 尝试制作一个非常简单的新类和一个带有一个按钮和文本视图的 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 的按钮。
推荐阅读
- python - 从字典列表中的字符串编号中删除逗号(,)
- bash - Azure DevOps 构建管道自托管代理“设备上没有剩余空间”
- python-3.x - 如何正确处理 Tensorflow 模型中的 NaN
- pycharm - 有没有办法在 PyCharm 中将一个字符映射到另一个字符?
- ag-grid - 在 ag-Grid 中编辑滚动条?
- django - API 设计最佳实践:使用 json_build_object 将 SQL SELECT 查询构造为类 json 是否是个好主意
- reactjs - 传递 typescript 的接口来响应状态
- reporting-services - SSRS 列标题对齐
- php - 在搜索结果 Laravel 中添加选择 orderby 或 sortby 过滤
- git - 使用来自 BitBucket 的 Rest API 获取最新的 10 个分支或所有分支