【发布时间】:2011-10-25 13:48:29
【问题描述】:
我正在尝试以编程方式在我的布局中设置一些 ImageButton 的图像。 为此,我将我的 ImageButtons 命名为 ic_1 到 ic_5。
在我的初始化方法中,我想遍历这 5 个 ImageButtons 并根据可能的图标列表设置它们的图像。 基本上,用户可以更改图标的显示顺序,这反过来会更改 ImageButtons 上的图像。
但是,我似乎无法引用这些按钮,因为它们的 ID 中有一个整数。 我用于此的代码是这样的:
for (int i = 1; i < 2; i++) {
String butid = "ic_"+i;
int resID = getResources().getIdentifier(butid, "id",
getPackageName());
ImageButton button = (ImageButton) findViewById(resID);
但是,这会返回 NullPointerException,因为 resID 返回 0。当我在 butid 中仅使用“ic_1”时,它也返回 0。
但是,如果我给 ImageButton 一个 ID 作为 ic_one,它确实有效。但如果我要使用纯文本 id,我将无法遍历 ImageButtons。
首先我认为这意味着 ID 没有正确转换为 R.java 文件,但其中存在按钮,它们各自的 ID 如下所示。
public static final int ic_1=0x7f05000e;
public static final int ic_2=0x7f05000f;
有谁知道在布局对象的 ID 中是否真的不可能使用 int,如果是这样,是否可以像我想要的那样循环 ImageButtons 而无需在 ID 中使用整数?一个简单的例子将不胜感激。
有关沃伦的更多信息:
布局规范:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainscreen);
setMenuImage();
initMainScreen();
}
应该改变图标的完整代码:
public void initMainScreen() {
if (standard == false) {
retrieveLinks();
int size = mso.getHome().getIcon().size();
if (size > 0) {
for (int i = 1; i < 2; i++) {
String butid = "ic_"+i;
int resID = getResources().getIdentifier(butid, "id",
getPackageName());
String buttype = mso.getHome().getIcon().get(i)
.getIconName();
System.out.println(buttype.toLowerCase());
int typeID = getResources().getIdentifier(buttype.toLowerCase(),
"drawable", getPackageName());
ImageButton button = (ImageButton) findViewById(resID);
if(button != null){
button.setImageResource(typeID);
}else{
System.out.println(butid+" "+resID);
}
}
}
}
}
布局文件中的规范:(所有按钮都一样)
<ImageButton android:layout_height="wrap_content"
android:layout_weight="33" android:layout_width="wrap_content"
android:src="@drawable/empty_icon" android:onClick="iconClick" android:background="@null" android:id="@+id/ic_1"></ImageButton>
【问题讨论】:
标签: android xml layout integer