View: settag () and gettag ()

Source: Internet
Author: User

The settag (onbect) in the view indicates that an extra data is added to the view. In the future, you can use gettag () to retrieve this data.

You can use multiple buttons to add a listener. Each button has a different settag. The listener uses gettag to identify which button is pressed.



Import Android. App. activity;
Import Android. OS. Bundle;
Import Android. View. view;
Import Android. widget. Button;

Public class main extends  Activity {
 
  @ Override
  Public void oncreate (bundle savedinstancestate ){
  Super. oncreate (savedinstancestate );
  Setcontentview (R. layout. Main );
  Button button1 = (button) findviewbyid (R. Id. button01 );
  Button button2 = (button) findviewbyid (R. Id. button02 );
  Button button3 = (button) findviewbyid (R. Id. button03 );
  Button button4 = (button) findviewbyid (R. Id. button04 );
  Mylistener listener = new mylistener ();
  Button1.settag (1 );
  Button1.setonclicklistener (listener );
  Button2.settag (2 );
  Button2.setonclicklistener (listener );
  Button3.settag (3 );
  Button3.setonclicklistener (listener );
  Button4.settag (4 );
  Button4.setonclicklistener (listener );
  }

  Public class mylistener implements view. onclicklistener {

  @ Override
  Public void onclick (view v ){
  Int tag = (integer) v. gettag ();
  Switch (TAG ){
  Case 1:
  System. Out. println ("button1 click ");
  Break;
  Case 2:
  System. Out. println ("button2 click ");
  Break;
  Case 3:
  System. Out. println ("button3 click ");
  Break;
  Case 4:
  System. Out. println ("button4 click ");
  Break;
  }
  }

  }

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.