我如何找到ViewByTag?

Rog*_*ger 7 android

假设我已经动态生成了一些LinearLayout,它们都有不同的标签.

for (int i = 0; i <= 5; i++)
{
        final LinearLayout LinLayBtn = new LinearLayout(this);
        LinLayBtn.setTag( "id"+String.valueOf(i) );
         ...
Run Code Online (Sandbox Code Playgroud)

现在我需要以某种方式访问​​这个布局,他们用不同的方法标记数字.

LinearLayout LinLayBtn = (LinearLayout)findViewWithTag("1");
Run Code Online (Sandbox Code Playgroud)

最好的方法是什么?

谢谢!

Foa*_*Guy 10

你试过这种方式并发现它有问题吗?

你需要制作这一行

LinearLayout LinLayBtn = (LinearLayout)findViewWithTag("1");
Run Code Online (Sandbox Code Playgroud)

匹配您在设置标记时使用的命名方案.所以你在你的例子中想要这样的东西:

LinearLayout LinLayBtn = (LinearLayout)findViewWithTag("id1");
Run Code Online (Sandbox Code Playgroud)

如果您需要执行许多这些查找,尽管在创建它们时将视图引用存储在数组中可能是更好的方法,因此您不必拥有所有的findView调用.或者像@Muhammad建议并使用parent.getChild(index i);

  • http://developer.android.com/reference/android/view/View.html#findViewWithTag%28java.lang.Object%29 findViewWithTag() 是 View 类的真正方法... (2认同)