什么是这种方法的主要目的为 setTag()
和 getTag()
的查看
类型的对象?
What is the main purpose of such methods as setTag()
and getTag()
of View
type objects?
我是正确的思维,我可以在任意数量的对象与单个视图相关联?
Am I right in thinking that I can associate any number of objects with a single View?
假设你生成一个一堆的观点是相似的。你可以设置一个 OnClickListener
为每个单独的观点:
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 ... );
...
然后,你必须创建一个唯一的onClick
方法,为每个视图即使他们这样做了类似的事情,比如:
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.
}
这是因为的onClick
只有一个参数,一个查看
,并且它必须获得实例中的其它信息变量或在封闭范围最终的局部变量。我们真正想要的是获取信息的的意见本身的。
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.
输入 getTag
/ setTag
:
button1.setTag(1);
button2.setTag(2);
现在,我们可以使用相同的OnClickListener每一个按钮:
Now we can use the same OnClickListener for every button:
listener = new OnClickListener() {
@Override
public void onClick(View v) {
doAction(v.getTag());
}
};
这基本上是一个办法的意见有的内存的。