get OnClick() from programmatically added buttons?

牧云@^-^@ 提交于 2019-12-06 15:01:53

This code is running. I hope it help you :)

    final ArrayList<String> Keys = new ArrayList<String>();
    for(int i = 0; i < 10; i ++){
        Keys.add("Keys is : " + String.valueOf(i));
    }

    LinearLayout Row = (LinearLayout)findViewById(R.id.KeysList);

    final Button[] my_button = new Button[Keys.size()];

    for (int bt = 0; bt < Keys.size(); bt ++){
        final int Index = bt;

        my_button[Index] = new Button(this);
        my_button[Index].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
        my_button[Index].setText(Keys.get(Index));
        my_button[Index].setId(Index);

        my_button[bt].setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (my_button[Index].getId() == ((Button) v).getId()){
                    Toast.makeText(getBaseContext(), Keys.get(Index), 0).show();
                }
            }
        });

        Row.addView(my_button[Index]);
    }

ExampleProject id : Your project

You should probably use View#setTag to set some arbitrary data you'd like associate with the Button. Then you can just instantiate only one OnClickListener that then uses getTag and acts on that data in whatever way you need.

Another way is to have your Activity listen to all button clicks and then you just filter respective to the ID. You should not get the text of the button and use that at all. You should use your own type of identifier, ideally the idea should be enough. Or perhaps you use setTag as @qberticus described.

Consider This example :

public class MainActivity extends Activity implements View.OnClickListener
{

LinearLayout linearLayout;
Button [] button;
View.OnClickListener listener;
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    linearLayout=(LinearLayout)findViewById(R.id.parent_lay);
    String[] array={"U123","U124","U125"};
    int length=array.length;
    System.out.println("11111111111111111111111111");
    button=new Button[length];
    for(int i=0;i<length;i++)
    {
        button[i]=new Button(getApplicationContext());
        button[i].setId(i);
        button[i].setText("User" + i);
        button[i].setOnClickListener(this);
        linearLayout.addView(button[i]);
    }
}
@Override
public void onClick(View view)
{
    view.getId();
    Button button=(Button)findViewById(view.getId());
    button.setText("Changed");
}
}

This works fine :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!