Android: Use setTag and getTag of View

Source: Internet
Author: User

Android: Use setTag and getTag of View

1. Used to differentiate many similar views

For example:

 

button1.setOnClickListener(new OnClickListener ... );button2.setOnClickListener(new OnClickListener ... );

They may execute similar logic, but you must set two independent OnClick events for the two buttons respectively,

 

 

public void onClick(View v) {    doAction(1); // 1 for button1, 2 for button2, etc.}

This is because onClick has only one View parameter. We can do this using setTag and getTag:

 

 

button1.setTag(1);button2.setTag(2);

We can set the two buttons to the same OnClickListener, for example:

 

 

listener = new OnClickListener() {    @Override    public void onClick(View v) {        doAction(v.getTag());    }};

In this way, it can be distinguished by getTag.

 

 

2. Used for reuse of ListView

When writing a custom adapter, we usually use it, for example:

 

static class ViewHolder {    TextView tvPost;    TextView tvDate;    ImageView thumb;}public View getView(int position, View convertView, ViewGroup parent) {    if (convertView == null) {        LayoutInflater inflater = myContext.getLayoutInflater();        convertView = inflater.inflate(R.layout.postitem, null);        ViewHolder vh = new ViewHolder();        vh.tvPost = (TextView)convertView.findViewById(R.id.postTitleLabel);        vh.tvDate = (TextView)convertView.findViewById(R.id.postDateLabel);        vh.thumb = (ImageView)convertView.findViewById(R.id.postThumb);        convertView.setTag(vh);    }            ....................}

3. Note:

 

In addition to the above situations, we try not to use them directly. The reason is:

1. code readability: it will cause troubles to other programmers.

2. Because setTag and getTag are set to an Object, a class conversion exception may occur.

However, there is a better method after android4.0: setTag (int key, Object tag) can be similar Key-Value Pair Access.

 

 

Related Article

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.