In the loop, the n-th number of buttons is created, and 1 general listener is created for them all, how can we find out which button is pressed in it?
2 answers
You can use setTag();
for (int i = 0; i < 4; i++) { Button btn = new Button(this); btn.setTag(i); btn.setOnClickListener(new View.OnclickListener() { @Override public void onClick(View v) { int i = v.getTag(); switch(i) { case 1: btn.setText(i); break; case 2: btn.setText(i); break; case 3: btn.setText(i); break; case 4: btn.setText(i);break; default: btn.setText("Others"); } } } |
The method of the class-listener for event handling takes the argument - View, which triggered the event => inside the method for handling clicks, determine the unique value of any property of the view. ID, for example:
new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch(v.getId()) { case ID_1: break; case ID_2: break; default: break; } } } - This is the problem, they are created by the cycle and they do not have unique properties - Stanislavs Jefimovs
- So difficult to appoint him? For example, the same View.setId () - AseN
- And how to create an id on the fly? (What to transfer to View.setId ()) - Stanislavs Jefimovs
- Any integer id. Usually they should be stored in constants. - AseN
|