将res / drawable / image.png转换为int时出错

时间:2014-08-11 08:23:36

标签: android adapter imagesource

我有一个来自strings.xml的类型化的drawable,我试图连接到我的适配器,现在我继续得到这个错误。

08-11 16:07:50.160: E/AndroidRuntime(2120): java.lang.NumberFormatException: Invalid int:   "res/drawable-xhdpi/ico_dashboard_squared.png"
08-11 16:07:50.160: E/AndroidRuntime(2120):     at java.lang.Integer.invalidInt(Integer.java:138)

陈述的drawable是正确的,这是我需要的图像。问题是错误。

这是我的strings.xml

<!-- Nav Drawer List Item Icons -->
<!-- Keep them in order as the titles are in -->
<array name="nav_drawer_icons">
    <item>@drawable/ico_dashboard_squared</item>
    <item>@drawable/ico_flashback</item>
    <item>@drawable/ico_qbank</item>
    <item>@drawable/ico_contact_us</item>
    <item>@drawable/ico_contact_us</item>
</array>

这是我如何绑定它。

// load slide menu items
    navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

    // nav drawer icons from resources
    navMenuIcons = getResources()
            .obtainTypedArray(R.array.nav_drawer_icons);

    adapter = new NavDrawerListAdapter(getApplicationContext(),
            navMenuTitles, navMenuIcons);
    mDrawerListLeft.setAdapter(adapter);

这是我的适配器的代码。

public class NavDrawerListAdapter extends BaseAdapter {
private Context context;
private String[] data;
private TypedArray icoArray;

public NavDrawerListAdapter(Context context, String[] data1, TypedArray data2){
    this.context = context;
    this.data = data1;
    this.icoArray = data2;
}

@Override
public int getCount()
{
    return data.length;
}


@Override
public Object getItem(int position)
{
    return data[position];
}


@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
     if (convertView == null) {
            LayoutInflater mInflater = (LayoutInflater)
                    context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
            convertView = mInflater.inflate(R.layout.drawer_list_item, null);
        }

        ImageView imgIcon = (ImageView) convertView.findViewById(R.id.icon);
        TextView txtTitle = (TextView) convertView.findViewById(R.id.title);

        imgIcon.setImageResource(icoArray.getInteger(position, 0)); // I guess it's in this line of code       
        txtTitle.setText(data[position]);

        return convertView;
}

}

为什么我收到此错误的任何想法?谢谢!

2 个答案:

答案 0 :(得分:1)

试试这个...

imgIcon.setImageResource(icoArray.getResourceId(position, 0));

getResourceId(position,def value)可帮助您获取int值中的数组ID。

答案 1 :(得分:-2)

您应该使用TypedArray而不是字符串数组