什么是setTag()getTag()查看方法的主要目的是什么? [英] What is the main purpose of setTag() getTag() methods of View?

查看:486
本文介绍了什么是setTag()getTag()查看方法的主要目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是这种方法的主要目的为 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());
    }
};

这基本上是一个办法的意见有的内存的。

这篇关于什么是setTag()getTag()查看方法的主要目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆