View的setTag()getTag()方法的主要目的是什么?

What is the main purpose of such methods as setTag() and getTag() of View type objects?

我是否认为可以将任意数量的对象与单个视图关联?

最佳答案

Let's say you generate a bunch of views that are similar. You could set an OnClickListener for each view individually:

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

Then you have to create a unique onClick method for each view even if they do the similar things, like:

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

This is because onClick has only one parameter, a View, and it has to get other information from instance variables or final local variables in enclosing scopes. What we really want is to get information from the views themselves.

Enter getTag/setTag:

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

现在,我们可以对每个按钮使用相同的OnClickListener:

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

基本上,这是视图记忆的一种方式。