android - 如何将 int 转换为 drawable?

标签 android int drawable android-gridview

我创建了一个带有图标列表的对话框,即可绘制对象。我创建了一个 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/

相关文章:

android - 在不使用位图的情况下防止 LayeredList 中的形状缩放

android - 可绘制图像给出 'No resource found..' 但它在文件夹中

android - 从 android NativeActivity 调用 Native 代码

c - 如何在 C 中反转数字同时仍包含零?

Android:传递没有序列化的对象

C++ 帮助将字符串转换为 uint8_t

c++ - 为什么我的函数打印 '0' ?

android - 奇怪的 R.java 问题导致可绘制资源未正确加载

java - Apache Commons Net,Android 导入不起作用

android - 我正在尝试从 TextView 中的 mysql 加载数据