更改不同活动的背景图像

时间:2015-07-28 04:47:50

标签: android

说我有活动1和活动2,图像A和图像B。

目前,在活动2中,我将背景图像设置为图像A,有没有办法从活动1内部将背景图像更改为图像B?

编辑:

我试过

    LinearLayout layoutBg = (LinearLayout) findViewById(R.id.activity2);
    layoutBg.setBackgroundResource(0);

从内部进行活动1,但我得到一个nullpointerexception:

 Caused by: java.lang.NullPointerException
        at com.imperostudio.meddit.StepTwo.onResume(StepTwo.java:141)
        at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1198)
        at android.app.Activity.performResume(Activity.java:5530)
        at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3048)
            at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3087)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1345)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5579)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
            at dalvik.system.NativeStart.main(Native Method)

3 个答案:

答案 0 :(得分:1)

您可以使用SharedPreferences保存原始数据:例如strings和CHECKING / MATCHING。

How to use SharedPreferences in Android to store, fetch and edit values

答案 1 :(得分:0)

您可以使用SharedPreferences存储所需的背景,在创建Activity2后,您可以再次从SharedPreferences读取背景并正确设置。这样做

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(KEY, VALUE);
editor.commit();

并按照以下方式阅读:

SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
try {
    String value = sharedPrefs.getString(KEY, defaultValue);
} catch (Exception e) {
    e.printStackTrace();
}

答案 2 :(得分:0)

我猜上面的答案不会起作用,因为user2809361想要实时更改图像。最好的选择是使用广播接收器。在活动2中使用此代码

private BroadcastReceiver mMyReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // change your image from here you can get the image link from intent
        }
    };
registerReceiver(mMyReceiver, new IntentFilter(...));

然后从活动1开始使用此代码

Intent intent = new Intent(this,MyReceiver.class);
intent.putExtra("image", "imagelink");
this.sendBroadcast(intent);

这将在活动2中触发您的广播接收器,它将在接收时调用该方法,然后您可以在那里完成任务。

希望这会有所帮助!!