Android that pressed an index button from an array

How to configure OnClickListener to just say which cursor button was pressed from an array of buttons. I can change the text and color of these buttons with an array. I installed them like that.

TButton[1] = (Button)findViewById(R.id.Button01); TButton[2] = (Button)findViewById(R.id.Button02); TButton[3] = (Button)findViewById(R.id.Button03); 

up to 36.

+4
source share
2 answers

OnClickListener will receive the button itself, such as R.id.Button01. It is not going to return your array index, since it does not know anything about how you have links to all buttons stored in the array.

You can simply use a button that is directly passed to your onClickListener, without additional requests in your array. For instance:

 void onClick(View v) { Button clickedButton = (Button) v; // do what I need to do when a button is clicked here... switch (clickedButton.getId()) { case R.id.Button01: // do something break; case R.id.Button01: // do something break; } } 

If you are really configured to search for the index of the pressed button array, you can do something like:

 void onClick(View v) { int index = 0; for (int i = 0; i < buttonArray.length; i++) { if (buttonArray[i].getId() == v.getId()) { index = i; break; } } // index is now the array index of the button that was clicked } 

But it really seems the most inefficient way around it. Perhaps if you provided more information about what you are trying to accomplish in your OnClickListener, I could help you.

+9
source

You can set the tag value and get the tag on click:

 TButton[1] = (Button)findViewById(R.id.Button01); TButton[1].setTag(1); onClick(View v) { if(((Integer)v.getTag())==1) { //do something } } 
+1
source

Source: https://habr.com/ru/post/1304093/


All Articles