2013-03-09 49 views
0

我想將圖像res/drawable-hdpi/nasa_image.jpg設置爲壁紙。參考可繪製的文件來創建Uri

我寫了下面的代碼,但它提高了FileNotFoundException

Uri u1 = Uri.fromFile(new File("res/drawable-hdpi/nasa_image.jpg")); 
Uri u2 = Uri.parse("android.resource://com.my.package/drawable/nasa_image.jpg"); 
Uri u3 = Uri.parse("android.resource://com.my.package/" + R.drawable.nasa_image); 
WallpaperManager w = WallpaperManager.getInstance(this); 

Bitmap bitmap; 
try { 
    bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(u)); 
    w.setBitmap(bitmap); 
} catch (FileNotFoundException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} catch (IOException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 

首先我想對u1。它沒有工作。然後我搜索並找到了this。然後我嘗試了u2u3

我檢查了日誌。每次它給出相同的FileNotFoundException

如何引用它?我錯在哪裏?我在弄錯根目錄嗎?

+0

爲什麼你不能只使用'w.setResource(R.drawable.nasa_image)'? – 2013-03-09 13:13:15

+0

我後來看到了方法並嘗試了它。但它也給'IllegalStateException:無法執行活動的方法'。你能提出什麼可能是錯的嗎?所有這些代碼都在點擊按鈕上。 – Shashwat 2013-03-09 13:22:35

+0

你可以發佈堆棧跟蹤嗎? – 2013-03-09 13:32:18

回答

0

我認爲這是一個錯誤的方式來做到這一點在android中。你爲什麼不使用資源標識符?

ImageView imgView=(ImageView)findViewById(R.id.imageView1); 
int id = getResources().getIdentifier(nasa_image, "drawable", getPackageName()); 
Drawable drawable=res.getDrawable(id); 
imgView.setImageDrawable(drawable); 

ImageView imgView=(ImageView)findViewById(R.id.imageView1); 
Drawable drawable= getResources().getDrawable(R.drawable.nasa_image); 
imgView.setImageDrawable(drawable); 
imgView.setImageDrawable(); 

更新從繪製轉換爲位圖只是用這個(假設你的繪製是一個instanceof Bitmapdrawable

Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap(); 

使用此方法,如果你不能確定drawable instance

public static Bitmap drawableToBitmap (Drawable drawable) { 
    if (drawable instanceof BitmapDrawable) { 
     return ((BitmapDrawable)drawable).getBitmap(); 
    } 

    Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888); 
    Canvas canvas = new Canvas(bitmap); 
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); 
    drawable.draw(canvas); 

    return bitmap; 
} 

,如果你確信你正確的文件路徑

private Drawable getDrawable(String path) { 
     File imgFile = new File(path); 
     if (imgFile.exists()) { 
     Bitmap bitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath()); 
     return new BitmapDrawable(resources, bitmap); 
     } 
     return null; 
    } 

你可以調整它的位圖或根據繪製回到你的問題,使用此方法

+0

您能否詳細說明一下? – Shashwat 2013-03-09 12:55:09

+0

@Shashwat llok在我的更新 – 2013-03-09 12:57:28

+0

這很好,但我需要'Bitmap'對象使用'w.setBitmap'方法。 – Shashwat 2013-03-09 13:23:51

-1

嘗試

Uri u1 = Uri.parse("R.drawable.nasa_image"); 
+0

這不起作用。 'R.drawable.nasa_image'應該沒有引號。 – Shashwat 2013-03-09 14:23:07

0

你不應該包括擴展名(.jpg) 使用:

Uri.parse("android.resource://" + BuildConfig.APPLICATION_ID + "/drawable/nasa_image");