背景
我通过遵循dymmeh单个初始化解决方案格式的每个按钮的onclick listerer的解决方案,在for循环中动态创建按钮:
LinearLayout someLayout = (LinearLayout) findViewById(R.id.theRoom);
for (int i = 0; i < neededButtons.length; i++){
neededButtons[i] = new Button(this);
neededButtons[i].setText(names[i]);
neededButtons[i].setOnClickListener(this);
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
}
此外,我通过在ActVity类中实现View.onclicklistener来制作一个onclick的听众。我的班级被定义为:
public class RecallActivity extends AppCompatActivity implements View.OnClickListener{
...
}
我成功地遵循了Pragnesh Ghota解决方案的其他步骤。但是...
问题
Pragnesh Ghota解决方案的第四步提到使用案例语句检查是否已单击了任何按钮。当已知按钮的量时,这起作用。但是,由于我遵循Dymmeh解决方案中列出的格式,因此我不知道在执行时间之前检查了多少按钮。
问题
如何在一个动态量的按钮中进行对控制流量语句?
创建每个按钮时只需为每个按钮创建一个新的OnClickListener。
LinearLayout someLayout = (LinearLayout) findViewById(R.id.theRoom);
for (int i = 0; i < neededButtons.length; i++){
neededButtons[i] = new Button(this);
neededButtons[i].setText(names[i]);
neededButtons[i].setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// add your click listener code here
}
})
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
}
您可以为按钮设置id
。
LinearLayout someLayout = (LinearLayout) findViewById(R.id.theRoom);
for (int i = 0; i < neededButtons.length; i++){
neededButtons[i] = new Button(this);
neededButtons[i].setText(names[i]);
neededButtons[i].setId(i);
neededButtons[i].setOnClickListener(this);
...
);
}
然后在OnClickListener
中查找ID视图。例如:
public class RecallActivity extends AppCompatActivity implements View.OnClickListener{
@overide
public void onClick(View view){
if(view.getId == 0){
.....
}
}
}
最简单的解决方案是使用settag和gettag作为您的按钮。您可以将对象与settag和getTag一起使用。每当您创建一个按钮时,都为其设置标签:
for (int i = 0; i < neededButtons.length; i++){
neededButtons[i] = new Button(this);
neededButtons[i].setText(names[i]);
neededButtons[i].setTag(names[i]);
// or you can use the index as the tag with:
// neededButtons[i].setTag(i);
neededButtons[i].setOnClickListener(this);
}
然后,您通过检查标签为每个按钮做点事:
@Override
public void onClick(View v) {
doSomething(v.getTag());
}
private void doSomething(Object tag) {
// in case your tag is the index, than you can convert it to
// integer and use switch case
int index = (int) tag;
switch(index) {
case 1:
...
break;
case 2:
...
break;
...
}
}