Search code examples
javaandroid-studiofor-looponclicklistener

How to handle setOnClickListener for dynamically added button in android?


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??


Solution

  • 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();
        }
    });