简体   繁体   中英

Knowing which button was clicked in Android

I am making an app which will contain 81 buttons on the same layout. They are all referred as an object I created called "Tile". Problem is those tiles are stored in an array, so I need to know which button was clicked in an int format to be able to call a tile ( tiles[??] ). I am using an onClick(View v) method. Also I have tried this:

Log.i("Tile", v.getId() + "was clicked")

The result it gave me in the logcat was a really long integer.

So how can I know which button was clicked in a number format? And what is the relationship between the casual id ( R.id.tile1 ) and this long integer, as it could help because it is already a number?

PS: I know I could use Switch to assign each id to an integer, but as they are 81, it will be a waste of time and will make the code very complicated.

I hope you can use tag option. You can set the tag for a view by view.setTag(1) and then on click event you can get back the tag set using view.getTag().

In android we can use the id of the button for getting the click event in on click listener.
Say you have, 5 Buttons: Make sure your Activity/Fragment implement OnClickListener

// in OnCreate

  Button mClickButton1 = (Button)findViewById(R.id.clickButton1);
  mClickButton1.setOnClickListener(this);
  Button mClickButton2 = (Button)findViewById(R.id.clickButton2);
  mClickButton2.setOnClickListener(this);
  Button mClickButton3 = (Button)findViewById(R.id.clickButton3);
  mClickButton3.setOnClickListener(this);
  Button mClickButton4 = (Button)findViewById(R.id.clickButton4);
  mClickButton4.setOnClickListener(this);
  Button mClickButton5 = (Button)findViewById(R.id.clickButton5);
  mClickButton5.setOnClickListener(this);</br>

//after this you will override the onclick method from OnClickListener

public void onClick(View v) {
  switch (v.getId()) {
      case  R.id.clickButton1: {
        // do something for button 1 click
        break;
      }
      case R.id.clickButton2: {
        // do something for button 2 click
        break;
      }

    //.... etc
   }
}

You can use button.setTag(position) to set position as tag.

And when onclick called get that tag value.

public void onclick(View v){
  int position = Integer.parseInt(v.getTag().toString());
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM