Android:在View类中使用getTag()和setTag() [英] Android:Purpose of getTag() and setTag() in View Class
问题描述
public void setTag(final Object tag) {
mTag = tag;
}
public Object getTag() {
return mTag;
}
这是Android中View类的两种方法. 以下分别是这两种方法的官方文档.
These are two methods from View Class in Android. Following is the official documentation of these two methods respectively.
/**
* Returns this view's tag.
*
* @return the Object stored in this view as a tag
*
* @see #setTag(Object)
* @see #getTag(int)
*/
/**
* Sets the tag associated with this view. A tag can be used to mark
* a view in its hierarchy and does not have to be unique within the
* hierarchy. Tags can also be used to store data within a view without
* resorting to another data structure.
*
* @param tag an Object to tag the view with
*
* @see #getTag()
* @see #setTag(int, Object)
*/
标记函数在baseadapter实现中被广泛使用,但是我无法理解其目的以及如何使用它们.您能否解释这个很好的例子,以帮助我理解这些功能的作用
tag functions are used extensively in baseadapter implementation but I couldn't understand its purpose and how to use them. Can you please explain this some good example to help me understand the role of these functions
推荐答案
尽可能简单地考虑它-一个标签".
Think of it as as plainly simple as it's possible - a "tag".
杂货店产品标签会告诉您什么? 基本上有很多东西,例如名称,价格,原产国,折扣等等.
What does a grocery shop product tag tell you? Basically a lot of things, such as name, price, origin country, discount, and many others.
想象一下,您正在制作一个使用ImageView在网格中显示此类产品的应用程序. 如何从ImageView轻松确定产品功能?对其进行标记是可能的解决方案之一.
Imagine you're making an application that displays such products in a grid using ImageView's. How to easily determine the product features from the ImageView? Tagging it is one of the possible solutions.
class Product {
String mName;
String mManufacturer;
String mOriginCountry;
double mPrice;
int mDiscount;
int mImageId; // A reference to a drawable item id
}
[...]
class My Activity {
@Override
protected void onCreate() {
[...] // Some code
// Grab the imageView reference and grab (or create) the tag for it
ImageView someItemView = (ImageView) findViewById(R.id.some_product_view);
Product someProductTag = new Product( ... some data ...);
// Add the tag to the ImageView
someItemView.addTag(someProductTag);
}
private void displayItemInfo(ImageView iv) {
// Grab the tag and display the info.
String productName = ((Product)iv.getTag()).mName();
Toast.show(mContext, "This is " + productName, Toast.LONG).show();
}
}
当然,这是非常简化的.理想情况下,您将拥有一个适配器,该适配器可以根据提供的标签创建视图,或者自动创建标签.
Of course this is very simplified. Ideally you would have an adapter which would create the view basing on your provided tags, or would create your tags automatically.
希望您能理解
这篇关于Android:在View类中使用getTag()和setTag()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!