可以转换String [] =“hello”;进入Drawable图像文件夹?

时间:2015-10-20 06:49:21

标签: android android-activity android-drawable

我的问题是,我想在Viewpager中添加图片。我正在尝试实现这个并且我已经成功实现了它。但是现在在ViewPager中,文本显示为string []值,我想要转换它字符串成Drawable图像,是否可以帮助我, 我将提供一些代码来理解我的问题,见下文,

class TestFragmentAdapter extends FragmentPagerAdapter implements       IconPagerAdapter  {

private static String image1="R.drawable.splash";
private static String image2="R.drawable.splash";
private static String image3="R.drawable.splash";
private static String image4="R.drawable.splash";

protected static final String[] CONTENT = new String[] { image1, image2, image3, image4 };
protected static final int[] ICONS = new int[] {
       // R.drawable.perm_group_calendar,
       // R.drawable.perm_group_camera,
       // R.drawable.perm_group_device_alarms,
        //R.drawable.perm_group_location
};

private int mCount = CONTENT.length;

public TestFragmentAdapter(FragmentManager fm) {
    super(fm);
}

@Override
public Fragment getItem(int position) {
    return TestFragment.newInstance(CONTENT[position % CONTENT.length]);
}

@Override
public int getCount() {
    return mCount;
}

@Override
public CharSequence getPageTitle(int position) {
  return TestFragmentAdapter.CONTENT[position % CONTENT.length];
}

@Override
public int getIconResId(int index) {
  return ICONS[index % ICONS.length];
}

public void setCount(int count) {
    if (count > 0 && count <= 10) {
        mCount = count;
        notifyDataSetChanged();
    }
}
}

1 个答案:

答案 0 :(得分:1)

    try {
        //packagename+sourceID,you should replace this String value to yours
        String sourceString = "com.yourpackagename.R.drawable.splash";
        StringBuffer stringBuffer = new StringBuffer();
        String[] splits = sourceString.split("[.]");

        for (int i = 0; i < splits.length - 2; i++) {
            if (i != 0)
                stringBuffer.append(".");
            stringBuffer.append(splits[i]);
        }
        stringBuffer.append("$");
        stringBuffer.append(splits[splits.length - 2]);

        Class<?> cls = Class.forName(stringBuffer.toString());

        int idValue = cls.getField(splits[splits.length - 1]).getInt(splits[splits.length - 1]);

        Bitmap image = BitmapFactory.decodeResource(context, idValue);
        //this is what you want!
        Drawable imageDrawable = new BitmapDrawable(image);

    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    }