此代码适用于所有Android版本,但不适用于Android 4.1
//我在模拟器上运行它。
图片img_1.png
存在于文件夹/res/drawable/
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
LinearLayout llMain = new LinearLayout(this);
LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
llMain.setLayoutParams(lp);
ImageView iv = new ImageView(this);
int resid = getResources().getIdentifier("img_1", "drawable", getPackageName());
Drawable imageDrw = getResources().getDrawable(resid);
iv.setImageDrawable(imageDrw);
llMain.addView(iv);
setContentView(llMain);
}
为什么?
答案 0 :(得分:0)
以下代码在4.1
中正常运行relative.setBackgroundResource(getResources().getIdentifier(
"image", "drawable", "com.package.application"));
所以你可以设置
iv.setImageResource(getResources().getIdentifier(
"image", "drawable", "com.package.application"))
答案 1 :(得分:0)
我有同样的问题,我通过将图像移动到drawable-xhdpi
来解决它。
在Android 4.1中从较小的dpi传输图像大小时可能存在一些问题。