Android 安卓。按标签查找视图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24116092/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 07:48:05  来源:igfitidea点击:

Android. Find view by tag

androidviewtagsfind

提问by BenG

I have a dynamically created View and want to find it by tag, is this possible? I know the function findViewById, is there something similar for tags?

我有一个动态创建的视图,想通过标签找到它,这可能吗?我知道这个功能findViewById,标签有类似的东西吗?

回答by user3384985

LinearLayout linLayout = (LinearLayout)findViewWithTag("layout1");

but I don't think you need tag for dynamic view. You can retrieve dynamic resource by following code

但我认为您不需要标记动态视图。您可以通过以下代码检索动态资源

for (int i=0; i < total_resource; i++) {
  //retrieve id dynamically
  int id = getResources().getIdentifier("resource"+i, "id", getPackageName());
  TextView myText = (TextView) findViewById(id); // get the element
}

回答by BenG

Create ids.xml to store your id:

创建 ids.xml 来存储您的 id:

<?xml version="1.0" encoding="utf-8"?> <resources> <item type="id" name="component1" /> <item type="id" name="component2" /> <item type="id" name="component3" /> </resources>

Set to dynamically created component like:

设置为动态创建的组件,如:

Button1.setId(R.id.layout1); buttom2.setId(R.id.layout2); button3.setId(R.id.layout3);

Another way is to set a tag to your component while creating dynamically

另一种方法是在动态创建组件时为组件设置标签

button1.setTag(1);

And use getTag()to get that component

并用于getTag()获取该组件