内循环动态按钮onclick事件 [英] dynamic button onclick event inside for loop
问题描述
我使用这个code至内循环创建动态按钮。
i'm using this code to create dynamic buttons within for loop..
LinearLayout linearLayout = (LinearLayout)findViewById(R.id.linearLayout2);
for (int i=0 ; i<10; i++){
LinearLayout l = new LinearLayout(this);
l.setOrientation(LinearLayout.HORIZONTAL);
TextView textview = new TextView(this);
textview.setText("Text view" + i);
textview.setId(i);
l.addView(textview);
Button button = new Button(this);
button.setText("View");
button.setId(i);
button.setWidth(90);
button.setHeight(60);
l.addView(button);
linearLayout.addView(l);//if you want you can layout params linearlayout
}
现在我想onclick事件添加到基于迭代的价值我每个按钮..任何一个可以建议我如何提前实现这个...感谢..
now i want to add onclick event to each button based on the iterating i value.. can any one suggest me how to implement this... thanks in advance..
推荐答案
创建按钮的arraay ...
create an arraay of buttons...
Button[] buttons=new Button[10];
和,而不是这一行
Button button = new Button(this);
在您的loop..use
in your for loop..use
button[i] = new Button(this);
和在同一回路根据你问的问题设置onclicklistener像this..and onclick事件添加到基于迭代的i值的每个按钮我认为你对所有相同的onclicklistener按钮。
and in the same loop set your onclicklistener like this..and based on the question you were asking add onclick event to each button based on the iterating i value i think you have same onclicklistener for all buttons..
button[i].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
//your onclicklistener code
}
});
这篇关于内循环动态按钮onclick事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!