我正在尝试从res / drawable文件夹中加载图片。我使用了Android开发者Link中的指南。 由于某种原因它不工作。我得到的唯一错误是“SPAN_EXCLUSIVE_EXCLUSIVE跨度不能有一个零长度”,我研究过。显然它与自定义键盘有关,但我根本不使用文本输入。应用程序本身不是崩溃。我希望你们能帮助我:) 布局文件只包含一个带有ImageView的RelativeLayout。
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);
}
}
答案 0 :(得分:1)
String uri = "@drawable-hdpi/testbild.png";
这是无效的。删除-hdpi
部分和.png
部分,然后重试。或者,切换到向getIdentifier()
提供所有三个参数:
final int imageResource = getResources().getIdentifier("testbild", "drawable", getPackageName());