Android 在ArrayList中添加按钮侦听器
我在按钮的循环中添加了OnClickListener,问题是I变量必须是final,但是a不能增加他 我的代码:Android 在ArrayList中添加按钮侦听器,android,Android,我在按钮的循环中添加了OnClickListener,问题是I变量必须是final,但是a不能增加他 我的代码: ArrayList<Button> buttonList = new ArrayList<Button>(); buttonList.add((Button)findViewById(R.id.mov1_btn)); buttonList.add((Button)findViewById(R.id.mov2_btn)); buttonList.add((Bu
ArrayList<Button> buttonList = new ArrayList<Button>();
buttonList.add((Button)findViewById(R.id.mov1_btn));
buttonList.add((Button)findViewById(R.id.mov2_btn));
buttonList.add((Button)findViewById(R.id.mov3_btn));
buttonList.add((Button)findViewById(R.id.mov4_btn));
buttonList.add((Button)findViewById(R.id.mov5_btn));
buttonList.add((Button)findViewById(R.id.mov6_btn));
for(int i = 0;i<buttonList.size();i++)
{
buttonList.get(i).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
buttonList.get(movCnt).setBackgroundResource(R.drawable.mov1n);
buttonList.get(i).setBackgroundResource(R.drawable.mov1o);
movCnt = i;
}
});
}
因为我不能是final,所以您必须声明另一个变量
for (int i = 0; i < buttonList.size(); i++) {
final int current = i;
buttonList.get(i).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
buttonList.get(movCnt).setBackgroundResource(R.drawable.mov1n);
buttonList.get(current).setBackgroundResource(R.drawable.mov1o);
movCnt = current;
}
});
}
不要将变量i设置为final,只需为视图设置一个标记即可。
这样,该值可以始终保留在视图中,并且可以在需要时使用
for(int i = 0;i<buttonList.size();i++)
{
buttonList.setTag(i);
buttonList.get(i).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
buttonList.get(movCnt).setBackgroundResource(R.drawable.mov1n);
buttonList.get(i).setBackgroundResource(R.drawable.mov1o);
movCnt = (Integer)v.getTag();
}
});
}
您需要使按钮成为最终按钮,而不是i,下面是一个应执行此操作的示例:
ArrayList<Button> list = new ArrayList<Button>();
list.add((Button) findViewById(R.id.BTN_login));
list.add((Button) findViewById(R.id.BTN_login));
list.add((Button) findViewById(R.id.BTN_login));
list.add((Button) findViewById(R.id.BTN_login));
for (int i = 0; i < list.size(); i++)
{
final Button tempButton = list.get(i);
tempButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
tempButton.setBackgroundResource(R.drawable.mov1n);
tempButton.setBackgroundResource(R.drawable.mov1o);
}
});
}
希望能有帮助
ArrayList<Button> list = new ArrayList<Button>();
list.add((Button) findViewById(R.id.BTN_login));
list.add((Button) findViewById(R.id.BTN_login));
list.add((Button) findViewById(R.id.BTN_login));
list.add((Button) findViewById(R.id.BTN_login));
for (int i = 0; i < list.size(); i++)
{
final Button tempButton = list.get(i);
tempButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
tempButton.setBackgroundResource(R.drawable.mov1n);
tempButton.setBackgroundResource(R.drawable.mov1o);
}
});
}