public class Main extends AppCompatActivity {
Button b1, b2, b3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout l1 = new LinearLayout(this);
l1.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams l2 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
setContentView(l1,l2);
LinearLayout.LayoutParams l3 = new LinearLayout.LayoutParams(200, ViewGroup.LayoutParams.WRAP_CONTENT);
b1 = new Button(this);
b1.setText("Button 1");
b1.setId(R.id.button1);
l1.addView(b1,l3);
b2= new Button(this);
b2.setText("Button 2");
b2.setId(R.id.button2);
l1.addView(b2,l3);
b3 = new Button(this);
b3.setText("Button 3");
b3.setId(R.id.button3);
l1.addView(b3,l3);
View.OnClickListener onClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.button1:
Toast.makeText(Main.this, "button 1", Toast.LENGTH_SHORT).show();
break;
case R.id.button2:
Toast.makeText(Main.this, "button 2", Toast.LENGTH_SHORT).show();
break;
case R.id.button3:
Toast.makeText(Main.this, "button 3", Toast.LENGTH_SHORT).show();
break;
}
}
};
b1.setOnClickListener(onClickListener);
b2.setOnClickListener(onClickListener);
b3.setOnClickListener(onClickListener);
}
}
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item type="id" name="button1" />
<item type="id" name="button2" />
<item type="id" name="button3" />
</resources>
b1 = new Button(this); и т.д.
Вам нужно прописать id для каждой кнопки. Это можно сделать напрямую b1.setId(123); b2.setId(456)
, но лучше в папку values создать xml файл с именем ids и прописать все id там (stackoverflow.com/questions/8937380/how-to-set-id-...case 123: break; case 456: break