2012-02-27 56 views
0

我想在我的應用程序中使用功能,用戶可以從手機內存中選擇背景(.png/.jpg文件)。我猜80%的任務已經通過這個鏈接完成http://www.dreamincode.net/forums/topic/190013-creating-simple-file-chooser/如何在Android中設置自定義背景?

上面鏈接的代碼只是顯示了SD卡的視圖,現在我想設置任何圖像文件作爲我的應用程序背景。我怎樣才能做到這一點?

+0

其實,爲了得到正確的你們必須遵循兩個答案,一個是appserv的答案我選擇了,但爲了確切的解決方案,看看我和a.ch之間的對話... – mrana 2012-02-27 11:07:57

回答

1

如果你想只需選擇圖像並設置背景,我覺得simpliest方式是這樣的:

..... 
Intent intent = new Intent(Intent.ACTION_PICK); 
intent.setType("image/*"); 
startActivityForResult(intent, SELECT_PICTURE_ACTIVITY_REQUEST_CODE); 
.... 

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { 
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 

    switch (requestCode) { 
     case SELECT_PICTURE_ACTIVITY_REQUEST_CODE: 
      if (resultCode == RESULT_OK) { 
       Uri selectedImage = imageReturnedIntent.getData(); 
       String[] filePathColumn = {MediaStore.Images.Media.DATA}; 
       Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null); 
       if (cursor.moveToFirst()) { 
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]); 
        String filePath = cursor.getString(columnIndex); 

        Bitmap bitmap = BitmapFactory.decodeFile(filePath); 
        setBackgroundDrawable(new BitmapDrawable(bitmap)); 
       } 
       cursor.close(); 
      } 
      break; 
    } 
} 
+0

看看我對a.ch的回答的評論。我認爲你接近解決。 – mrana 2012-02-27 10:43:55

0

根據您的應用程序,每個現有佈局周圍都有一個FrameLayout,以適當設置的ImageView開始。

0

如果你想要做你的活動parentview動態使用

setBackgroundColor(int color) 

setBackgroundResource(int resourceID) 

+0

對不起,但我指出的東西並不是那麼容易,你可能會想到。 – mrana 2012-02-27 10:27:17

0

宥可以試試這個:

Bitmap srcBitmap = BitmapFactory.decodeStream(new FileInputStream(new File("path/to/file.jpg"))); 
BitmapDrawable bmpDrawable = new BitmapDrawable(srcBitmap); 
YourView.setBackgroundDrawable(bmpDrawable); 
0

我想你的問題是你不知道如何加載從畫廊中挑選的圖像。 @ appserv的答案可以解決你的問題,但是如果你需要從任何來源(包括你的應用程序資源)加載圖片,看看它是如何的implemented in ImageView

+0

其實我創建了一個名爲setBackground的菜單項,點擊後會打開一個對話框,其中包含兩個按鈕1.設置自定義背景2.默認背景。當用戶首先點擊手機存儲器loc或SDCarddir(無論什麼)應該打開,然後用戶可以選擇存在的圖片現在應用程序應該有新的背景,也可以通過使用第二個按鈕用戶可以切換到默認的背景。 – mrana 2012-02-27 10:36:29

+0

這正是appserv的解決方案所做的,除了恢復默認背景。將與'startActivityForResult(..)'相關的代碼放入'onContextItemSelected(..)'方法中。 – 2012-02-27 10:56:08

+0

謝謝,但問題是誰應該得到信用? :)你或appserv – mrana 2012-02-27 11:02:12