Android 通过标签查找ImageView

Android find ImageView by tag

我只是想通过标签查找 ImageView,类似于 findViewById。我找到了 findViewWithTag 函数,但是当我尝试使用它时出现 "cannot resolve method..." 错误。

setContentView(R.layout.activity_detailed_view);

//This works fine
TextView name =  (TextView) findViewById(R.id.name);

//this doesn't
ImageView img = (ImageView) findViewWithTag("myTag");

ActivityView 都有 findViewById()Activity 没有 findViewWithTag()。试试这个:

ImageView img = (ImageView) findViewById(R.id.activity_detailed_view).findViewWithTag("myTag");

为此,您需要进入 activity_detailed_view.xml 布局并为第一个容器指定一个 ID“@+id/activity_detailed_view”。

换句话说,使用 findViewById 获取 activity 的视图,然后在该视图上调用 findViewWithTag()