简体   繁体   English

安卓。 按标签查找视图

[英]Android. Find view by tag

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 ,标签有类似的东西吗?

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
}

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()获取该组件

You can find by tag inside other view.您可以在其他视图中按标签查找。

Say, you have LinearLayout with several buttons that you dynamically put inside it and assigned tag for each of them.比如说,你有几个带有几个按钮的 LinearLayout,你可以动态地把这些按钮放在里面,并为每个按钮分配标签。 You MUST know id for that LinearLayout b/c 1st your find it by id.你必须知道那个 LinearLayout b/c 的 id 1st 你通过 id 找到它。 Then find buttons by tag inside that LinearLayout view:然后在该 LinearLayout 视图中按标签查找按钮:

LinearLayout ll=(LinearLayout)findViewById(R.id.mylinearlayout);
Button btn= (Button)ll.findViewWithTag("mybtntag");//tag must be string

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM