2014-12-19 74 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