[英]how to add action dynamically for multiple checkbox on android?
In my project rows are added dynamically to the table depending on selected items from database. 在我的项目中,行根据数据库中的选定项动态添加到表中。 This table contains a column with checkbox
此表包含一个带复选框的列
How can I set action for each checkbox that are added dynamically ? 如何为动态添加的每个复选框设置操作? The table looks like this
该表看起来像这样
column1 column2 column3 id1 data1 checkbox1 id2 data2 checkbox2 . . . . . .idn datan checkboxn
Then I want to set action for all selected checkbox and the no of checkbox not defined that changes on every activity.. 然后我想为所有选中的复选框设置操作,并且没有定义每个活动更改的复选框。
CheckBox check[i]= new CheckBox(this);
check[i].setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
//code
}
});
Is it possible to use this logic? 是否可以使用这种逻辑?
What you can do is: 你能做的是:
As you create each checkbox, give it a unique tag by using setTag(Object tag)
method. 在创建每个复选框时,使用
setTag(Object tag)
方法为其指定唯一标记。
Set the same OnClickListener
for each checkbox. 为每个复选框设置相同的
OnClickListener
。
Inside onClick(View v)
method, get the tag by using v.getTag()
. 在
onClick(View v)
方法中,使用v.getTag()
获取标记。 This way you will know which checkbox was clicked. 这样您就可以知道单击了哪个复选框。
I would say yes. 我会说是的。
FrameLayout yourlayout = (FrameLayout) findViewById(R.id.container);
CheckBox[] check = new CheckBox[10];
check[0] = new CheckBox(this);
yourlayout.addView(check[0]);
check[0].setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Hi, this is working fine", Toast.LENGTH_SHORT).show();
}
});
I don't know what kind of layout you are using, but this example works for me. 我不知道你正在使用什么样的布局,但这个例子适合我。
Edit: as said above, setting a tag is a nice way to know what checkbox was pressed. 编辑:如上所述,设置标签是了解按下复选框的好方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.