我正嘗試從我的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);
}
}
嘗試,而不是view.post runOnUiThread。有時View.post根本不會被調用。只有Handler.post和Activity.runOnUiThread總是爲我工作。 – 2013-04-23 09:27:19