我有一个创建34个按钮的循环,我如何为每个按钮设置不同的onclick?
while(i<34)
{
Button btnTag = new Button(this);
btnTag.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
btnTag.setText(names[i]);
btnTag.setId(i);
btnTag.callOnClick();
layout.addView(btnTag);
btnTag.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
HOW TO MAKE EACH ONE DO A DIFFERENT THING
}
});
i++;
}
答案 0 :(得分:1)
由于v.getId()
while(i<34)
{
Button btnTag = new Button(this);
btnTag.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
btnTag.setText(names[i]);
btnTag.setId(i);
btnTag.callOnClick();
layout.addView(btnTag);
btnTag.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switch(v.getId())
{
// Your code
}
}
});
i++;
}
答案 1 :(得分:0)
public void createButtons() {
while(i<34)
{
Button btnTag = new Button(this);
btnTag.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
btnTag.setText(names[i]);
btnTag.setId(i);
btnTag.setTag("TAG"+i); // set a tag
btnTag.callOnClick();
layout.addView(btnTag);
btnTag.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
buttonClicked(v);
}
});
i++;
}
}
// hand button click
public void buttonClicked(View view) {
final Object tag = view.getTag();
if ("TAG1".equals(tag)) {
//button 1
} else if ("TAG2".equals(tag)) {
//button 2
}
// add more if else
}
您将创建一个新的OnClickListener对象的每个按钮,更喜欢使用一个单击侦听器对象:
public void createButtons() {
// just need one listener object
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
buttonClicked(v);
}
};
while(i<34)
{
Button btnTag = new Button(this);
btnTag.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
btnTag.setText(names[i]);
btnTag.setId(i);
btnTag.setTag("TAG"+i); // set a tag
btnTag.callOnClick();
layout.addView(btnTag);
btnTag.setOnClickListener(listener);
i++;
}
}
答案 2 :(得分:0)
虽然你所做的事情并不实际,但我建议这样做:
开展您的活动 <item name="android:colorControlNormal">@color/colorAccent</item>
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:colorControlNormal">@color/colorAccent</item>
</style>
在您的活动中实施覆盖方法。
implements
创建按钮时使用
View.OnClickListener
您的编辑功能。
@override
public void onClick(View view){
switch(view.getId()){
// You will have to understand the buttons Ids
case R.id.buttonId1:
MyFunction();
break;
case R.id.buttonId2:
MyFunction2();
break;
default:
break;
}