我创建了一个带有图标列表的对话框,即可绘制对象。我创建了一个 GridView 来显示这些图标。
现在我想获取选定的图标并将其设置为我的 Activity 中的 ImageView 。
那么我怎样才能将它转换成可绘制的,以便我可以在我的 Activity 的 ImageView 上设置选定的图标?
对话代码:
private void showAlertDialog() {
GridView gridView = new GridView(this);
gridView.setGravity(Gravity.CENTER);
gridView.setPadding(0,20,0,20);
int[] mThumbIds = {
R.drawable.roundicons05,R.drawable.roundicons08,R.drawable.roundicons02,R.drawable.roundicons03,R.drawable.roundicons04,
R.drawable.roundicons16,R.drawable.roundicons37,R.drawable.roundicons06,R.drawable.roundicons07,R.drawable.roundicons05,
R.drawable.roundicons09,R.drawable.roundicons10,R.drawable.roundicons11,R.drawable.roundicons12,R.drawable.roundicons13,
R.drawable.roundicons14,R.drawable.roundicons15,R.drawable.roundicons16,R.drawable.roundicons17,R.drawable.roundicons18,
R.drawable.roundicons19,R.drawable.roundicons20,R.drawable.roundicons22,
};
gridView.setAdapter(new ImageAdapter(CheckListActivity.this,mThumbIds));
gridView.setNumColumns(4);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// do something here
// icon.setImageDrawable(id);
imageId = position;
Drawable drawable = getResources().getDrawable(imageId);
icon.setImageDrawable(drawable);
}
});
final MaterialDialog dialog = new MaterialDialog.Builder(CheckListActivity.this)
.customView(gridView, false)
.title("Select Icon")
.negativeText("CANCEL")
.canceledOnTouchOutside(true)
.build();
dialog.show();
}
我试过这样
imageId = position;
Drawable drawable = getResources().getDrawable(imageId);
icon.setImageDrawable(drawable);
但这会抛出没有发现资源的异常。
谢谢你..
最佳答案
不是使用 position
作为 ResourceID(它不是),而是在 positions
获取 mThumbIds
数组的一项。所以你的代码应该是这样的:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// do something here
imageId = mThumbIds[position];
Drawable drawable = getResources().getDrawable(imageId);
icon.setImageDrawable(drawable);
}
希望对您有所帮助。
关于android - 如何将 int 转换为 drawable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37439560/