开发者

Android: Knowing which button is pressed for buttons that are created programatically

I am trying to do this:

Programatically create 4 buttons on a layout. Then, create an onclick listener for each of the button. Then, based on which button is pressed, will do s开发者_如何学编程ome logic.

I have created a LinearLayout in my XML file and called it "layout".

So, my codes go something like this:

    layout = (LinearLayout)findViewById(R.id.layout);

    //Create the array of buttons
    Button [] subjectButtons_BT = new Button[4];

    for(int i=0; i<4; i++){
        subjectButtons_BT[i] = new Button(this);
        // Add the button to the layout
        layout.addView(subjectButtons_BT[i]);
        subjectButtons_BT[i].setOnClickListener(new Button.OnClickListener() {
                public void onClick(View v) {
               // if it is the first button, do LOGIC1
               // if it is the second button, do LOGIC2 etc 
                }
        });
    }

So far, I have managed to create the 4 buttons and I can click on the buttons. However, I do not know how to the logic in the setOnClickListener part.

I wanted to know which button is pressed. So, I tried using v.getId() but it always returns a -1.

Can someone advise if this is the right way to go? And if so, how to do the logic?

Thanks.


You have two options for identify which dynamic button is clicked.

 1) Set ID to the button and compare ID 
 2) Set Tag to the button if you have come more information about button
     and want to access it

1) You can set id to the button and in onClick() method you can get id by button.getId() method and you can compare ids and perform action according to click.

2) If you set tag then you have to get tag by calling button.getTag() method and by this way you can pass object with the button


You can set the id of the buttons after you create them, and then check for that id within the OnClickListener

layout = (LinearLayout)findViewById(R.id.layout);

//Create the array of buttons
Button [] subjectButtons_BT = new Button[4];

for(int i=0; i<4; i++){
    subjectButtons_BT[i] = new Button(this);
    subjectButtons_BT[i].setId(i);
    // Add the button to the layout
    layout.addView(subjectButtons_BT[i]);
    subjectButtons_BT[i].setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                int id = v.getId();
                if (id == 0) {
                } else if (id == 1) {
                }
                //etc.
            }
    });
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜