我正在尝试使用方法
获取图像视图int mId = getResources().getIdentifier(s, "id",getPackageName());
ImageView img = (ImageView) findViewById( mId);
img.setImageResource(kBonusImage);
但是我在mId得到0。
这是我的xml布局: -
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="35dp"
android:shrinkColumns="*"
android:stretchColumns="*" >
<TableRow
android:id="@+id/trFirstRow"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView
android:id="@+id/imgFirst"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:background="@drawable/cell_border"
android:gravity="center"
/>....
答案 0 :(得分:5)
问题是您尝试使用名称为ImageView
的{{1}}加载id
。但是,XML布局文件没有"id"
ImageView
。这意味着android:id=@+id/id"
无法找到您要求的findViewById()
。指定的ImageView
必须与XML视图文件中的一个完全匹配。
使用id
完全没必要。在Java代码中获取getResources().getIdentifier()
对象的典型方法是使用在构建应用程序时从XML布局文件生成的View
类。在这种情况下,您已在XML布局文件中定义了R.id
资源,其标识为ImageView
。所以你可以这样叫imgFirst
:
findViewById()
这假定您之前已调用ImageView img = (ImageView) findViewById(R.id.imgFirst);
来加载包含此setContentView()
资源的XML布局文件。