1

I have added button view to a linearlayout and now I want to setOnClickListener on each added button here's my code

for(int i=0;i<15;i++){
   Button btn = new Button(this);
   btn.setText("button " + i);
   myview.addView(btn);

   btn.setOnClickListener(new OnClickListener(){
       @Override
       public void onClick(View v){
            Toast.makeText(MainActivity.this, "you clicked button " + i, Toast.LENGTH_SHORT).show();
       }
   });
}

but getting result is only you clicked button 15 for all buttons, but i want to get only that position result which I have clicked on button Like:

for button1 ==> you clicked button 1
for button2 ==> you clicked button 2

How to do that??

0

1 Answer 1

1

You can setTag and getTag to identify your Buttons.

Button btn = new Button(this);
btn.setText("button " + i);
btn.setTag("button" + i);
myview.addView(btn);

btn.setOnClickListener(new OnClickListener(){
    @Override
    public void onClick(View v){
        Toast.makeText(MainActivity.this, "you clicked " + v.getTag(), Toast.LENGTH_SHORT).show();
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

if your intention is to only read out "you clicked button (number)" seems like that is also the text on your button, you can cast the view as a button and do gettext() on it, and then concatenate with "you clicked ". something like this "you clicked " + (Button) v.getText()
@Mohammed Abdul Bari, No i can't do that. there button text and button tag values are different

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.