2016-12-11 44 views
2

我使用下面的代碼:如何設置所有活動的永久背景?

Public void xyz(View v) { 
    Intent intent = new Intent(); 
    intent.setType("image/*"); 
    intent.setAction(Intent.ACTION_GET_CONTENT); 
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), 0); 
} 

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    switch(requestCode){ 
     case 0: 
      data.getDataString(); 
      if(resultCode == RESULT_OK){ 
       try { 
        Bitmap bitmap = MediaStore.Images.Media.getBitmap(_activity.getContentResolver(), data.getDataString()); 
        RelativeLayout bg = (RelativeLayout) findViewById(R.id.might); 
        Drawable drawable = new BitmapDrawable(getResources(), bitmap); 
        bg.setBackgroundDrawable(drawable); 
       } catch (FileNotFoundException e) { 
        // TODO Auto-generated catch blocke.printStackTrace(); 
       } catch(IOException e) { 
        // TODO Auto-generated catch blocke.printStackTrace(); 
       } 
      }     
      break; 
    } 
} 

問題:

  1. 它設置爲只有一個活動的背景。

  2. 經過onDestroy()方法後,它在重啓時設置默認背景。

+3

學習如何格式化您的代碼:http://meta.stackexchange.com/questions/22186/how-do-i-format-my-code-blocks –

+0

您可以編寫一個活動類,它是所有超類您的其他活動 –

+1

您可以將所選圖像的URL存儲在單個類/ SharedPreferences中,並在創建活動時加載它。可能你甚至可以使用像畢加索這樣的庫的緩存來避免在圖像仍然在內存中時加載圖像。 –

回答

1

保存圖像到內部存儲器中(放onactivityresult)

FileOutputStream outputStream = null; 
    try { 
outputStream = openFileOutput("filename.jpg", Context.MODE_PRIVATE); 
// Use the compress method on the BitMap object to write image to the OutputStream 
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream); 
        } catch (Exception e) { 
         e.printStackTrace(); 
        } finally { 
         try { 
          outputStream.close(); 
         } catch (IOException e) { 
          e.printStackTrace(); 
         } 

//負載圖像並設置爲背景(onsatrtactivity)

try { 
     FileInputStream l = openFileInput("filename.jpg"); 
     Bitmap A = BitmapFactory.decodeStream(l); 
     LinearLayout bg = (LinearLayout) findViewById(R.id.layoutid); 
     Drawable drawable = new BitmapDrawable(getResources(), A); 
     bg.setBackgroundDrawable(drawable); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } 

感謝馬爾欽Jedynak !!!

+0

感謝編碼這下! –

2

您可以使用一個MainActivity。然後,使用片段作爲屏幕。將您的顏色或背景繪製爲MainActivity的佈局。但是,做以下所有片段的佈局:

<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:background="#00000000" 

前兩個00的是用於製作背景透明。

0

Rupinderjeet asnwer是正確的。它可以使你在默認背景下工作。

但是這裏是一個簡單和最好的方法來做到這一點。

使您style.xml的風格由你的應用程序的主題

放在values

<style name="DefaultBackgroundTheme" parent="Base.Theme.AppCompat.Light"> 
    <item name="android:windowBackground">@drawable/splash_bitmap</item> 
</style> 

變化Base.Theme.AppCompat.Light你可以把colorbitmapsdrawables以及在這裏。

和您的清單類中由

<activity 
    android:name="yourActivityName" 
    android:theme="@style/DefaultBackgroundTheme" /> 

希望這有助於你改變你的主題。