2014-12-19 58 views
0

我正在處理一些代碼,我想在引用共享首選項時動態更改背景圖像。活動我有一個例子是這樣的:如何在Android中設置不同類的背景/佈局

public class Splash extends Activity { 
    protected void onCreate(Bundle inputVariableToSendToSuperClass) { 

     super.onCreate(inputVariableToSendToSuperClass); 
     setContentView(R.layout.splash); 
     Initialize(); 

     //Setting background 
     SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); 
     String user_choice = prefs.getString("pref_background_choice","blue_glass"); 
     LinearLayout layout = (LinearLayout) findViewById(R.id.activity_splash_layout); 
     ManagePreferences mp = new ManagePreferences(); 
     mp.setTheBackground(Splash.this, user_choice, layout); 

     //More code after this... 
    } 
} 

的ManagePreferences類看起來是這樣的:

public class ManagePreferences { 

    //Empty Constructor 
    public ManagePreferences(){ 
    } 

    public void setTheBackground(Context context, String background_choice, LinearLayout layout){ 
     if (background_choice == "blue_glass"){ 
      layout.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.blue_glass)); 
     } else if (background_choice == "blue_oil_painting") 


      //etc... with more backgrounds 
     } 
} 

的問題是,用於設置背景的代碼不是從不同類的工作。如果我將它複製到Splash活動中,我可以讓代碼工作,但如果我引用該類並調用該方法,則不能執行該代碼;我寧願不要混淆我的代碼。

我想要做的是通過調用此ManagePreferences類來更改Splash Activity中的佈局(setBackgroundDrawable)。

謝謝大家!

+0

我更新了我的答案。它有幫助嗎?或者我誤解了你? – Suvitruf 2014-12-19 12:37:03

回答

2

1)你做錯了。您不應使用new直接創建Activity

2)您應該使用Intent打開新的活動併爲其設置參數。

Intent intent = new Intent(context, ManagePreferences.class); 
intent.putExtra("user_choice", user_choice); 
startActivity(intent); 

而且在ManagePreferences得到它:

Bundle extras = getIntent().getExtras(); 
if (extras != null) { 
    String user_choice = extras.getString("user_choice"); 
} 

UPD:如果您正在使用ManagePreferences就像實用程序類,使setTheBackground靜:

public static void setTheBackground(Context context, String background_choice, LinearLayout layout){ 
     if (background_choice == "blue_glass"){ 
      layout.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.blue_glass)); 
     } else if (background_choice == "blue_oil_painting") 


      //etc... with more backgrounds 
     } 
     layout.requestLayout(); 
    } 

,並調用它:

ManagePreferences.setTheBackground(this, user_choice, layout); 

UPD:作爲回答here,你不能這樣做。當您使用findViewById()引用佈局文件時,android系統僅在您當前的ContentView中查找此文件。 (即您爲當前活動使用setContentView()設置的視圖)。

+0

關於通過意圖傳遞數據,您絕對正確,問題是,我不打開其他類。 ManagePreferences活動永遠不會作爲一個類打開。我只是試圖使用它,所以通過我必須運行的10個if語句來設置背景圖像。我試圖找出一種方法來獲取layout.setBackgroundDrawable()引用最初調用該方法的類。基本上,讓ManagePreferences類實際設置類的調用它的佈局 – Silmarilos 2014-12-19 10:31:43

+0

@Silmarilos我真的不明白你爲什麼使用Activity並從不打開它=/ – Suvitruf 2014-12-19 10:35:28

+0

我更新了問題以顯示ManagePreferences類不是一個活動。這有助於使它更清楚一點嗎?我不試圖打開一個活動,我試圖使用ManagePreferences類來更改飛濺類的佈局 – Silmarilos 2014-12-19 10:39:42

相關問題