ImageView无法加载图像(jpg,png,...)
问题描述:
我正尝试从我的res/drawable文件夹中加载图像。我使用了Android开发人员指南Link。 出于某种原因,它不工作。我得到的唯一错误是“SPAN_EXCLUSIVE_EXCLUSIVE跨度不能有零长度”,我研究它。显然它必须与自定义键盘有关,但我根本没有使用文本输入。应用程序本身没有崩溃。我希望你们能帮助我:) 布局文件只包含一个带有ImageView的RelativeLayout。ImageView无法加载图像(jpg,png,...)
public class PixelActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pixel);
String uri = "@drawable-hdpi/testbild.png";
final int imageResource = getResources().getIdentifier(uri, null, getPackageName());
final ImageView iv = (ImageView) findViewById(R.id.imageview1);
//int imageHeight = options.outHeight;
//int imageWidth = options.outWidth;
//String imageType = options.outMimeType;
new Thread(new Runnable()
{
public void run()
{
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), imageResource, options);
iv.post(new Runnable()
{
public void run()
{
iv.setImageBitmap(decodeSampledBitmapFromResources(getResources(),imageResource,iv.getWidth(),iv.getHeight()));
//iv.setImageResource(R.drawable.testbild);
}
});
}
});
}
public static int calculateInSampleSize(BitmapFactory.Options options,int reqWidth, int reqHeight)
{
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if(height > reqHeight || width > reqWidth)
{
final int heightRatio = Math.round((float)height/(float)reqHeight);
final int widthRatio = Math.round((float)width/(float)reqWidth);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmapFromResources(Resources res, int resId, int reqWidth, int reqHeight)
{
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
options.inSampleSize = calculateInSampleSize(options,reqWidth,reqHeight);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
}
答
String uri = "@drawable-hdpi/testbild.png";
这是无效的。删除-hdpi
部分和.png
部分,然后重试。或者,切换到提供所有三个参数getIdentifier()
:
final int imageResource = getResources().getIdentifier("testbild", "drawable", getPackageName());
+0
试过了,它没有工作:(感谢您的帮助到目前为止。 – cgew85 2013-04-23 14:18:49
尝试,而不是view.post runOnUiThread。有时View.post根本不会被调用。只有Handler.post和Activity.runOnUiThread总是为我工作。 – 2013-04-23 09:27:19