我正在尝试为drawables数组实现typedarray

时间:2016-04-14 08:43:30

标签: android arrays android-drawable typed-arrays

我通过简单的int []然后Typed数组尝试了不​​同的方法,现在我的Typed数组给出资源ID为2130837586.如何将其转换为R.drawable的形式?如果我尝试使用getDrawable,它会给出:

android.graphics.drawable.BitmapDrawable@42007a80

我在logcat中检查了这些。

编辑 - ids.getIndexCount()也为零。

这是我的代码。请帮忙

     GridView gridView = (GridView) findViewById(R.id.grid);
    gridView.setAdapter(new ImageAdapter(this, getResources().obtainTypedArray((R.array.image_ids))));

这是我的字符串

      <array name="image_ids">
    <item>@drawable/one</item>
    <item>@drawable/two</item>
    <item>@drawable/three</item>
    <item>@drawable/four</item>
    <item>@drawable/five</item>
    <item>@drawable/six</item>
    <item>@drawable/seven</item>
    <item>@drawable/eight</item>
    <item>@drawable/nine</item>
    <item>@drawable/ten</item>
    <item>@drawable/eleven</item>
    <item>@drawable/twelve</item>
</array>

这是我的ImageAdapter

     public class ImageAdapter extends BaseAdapter {
private Context mContext;
TypedArray ids;

public ImageAdapter(Context con,TypedArray rids){
    mContext = con;
    ids = rids;
    Log.d("Check this out,",""+ids.getDrawable(0));
}

@Override
public int getCount() {
    return ids.getIndexCount();
}

@Override
public Object getItem(int position) {
    return ids.getDrawable(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ImageView imageView;

    if (convertView == null) {
        imageView = new ImageView(mContext);
        imageView.setLayoutParams(new GridView.LayoutParams(180, 180));
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setPadding(8, 8, 8, 8);
    }
    else
    {
        imageView = (ImageView) convertView;
    }
    imageView.setBackgroundResource(ids.getResourceId(position,-1));

     return imageView;
}
}

1 个答案:

答案 0 :(得分:0)

替换此代码

imgIcon.setImageResource(IDS [位置]);