web-dev-qa-db-ja.com

intをドローアブルに変換する方法は?

アイコン、つまりドローアブルのリストを含むダイアログを作成しました。これらのアイコンを表示するグリッドビューを作成しました。

次に、選択したアイコンを取得して、アクティビティの画像ビューに設定します。

どうすればこれをドローアブルに変換して、選択したアイコンをアクティビティの画像ビューに設定できるようになりますか?

ダイアログコード:

 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);

しかし、これはリソースが見つかりません例外をスローしません。

ありがとうございました..

9
user6265109

resourceIDとしてpositionを使用する代わりに(そうではありません)、mThumbIdspositions配列の項目を取得します。したがって、コードは次のようになります。

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);

 }

これがお役に立てば幸いです。

15
ishmaelMakitla

メソッドgetDrawable(int)は非推奨です。簡単に使えるようになりました

    icon.setImageResource(imageId);
1
Raluca Lucaci

この線

imageId = position;

このようになるはずです

imageId = mThumbIds[position];
0
Moh'd Awad