1.在drawable中添加需要设置的背景图片,我这里只添加了两张,分别命名为bg1和bg2
2.利用菜单实现背景的切换res/menu/menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/bg1"
android:orderInCategory="100"
android:showAsAction="never"
android:title="背景1"/>
<item
android:id="@+id/bg2"
android:orderInCategory="100"
android:showAsAction="never"
android:title="背景2"/>
<item
android:id="@+id/bg3"
android:orderInCategory="100"
android:showAsAction="never"
android:title="恢复原状"/>
</menu>
3.工具类MyUtil,实现根据图片的索引更改背景
package cn.lynu.changeactivitybackground;
public class MyUtils {
public static void setBackground(Activity activity,int index,Drawable drawable) {
switch (index) {
case 1:
activity.getWindow().setBackgroundDrawableResource(R.drawable.bg1);
break;
case 2:
activity.getWindow().setBackgroundDrawableResource(R.drawable.bg2);
break;
case 0:
activity.getWindow().setBackgroundDrawable(drawable);
break;
}
}
}
4.主界面代码
package cn.lynu.changeactivitybackground;
public class MainActivity extends Activity {
Drawable drawable;
SharedPreferences sp;
View view;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view=this.getWindow().getDecorView();//getDecorView 获得window最顶层的View
drawable=view.getBackground();
sp=getSharedPreferences("background", MODE_PRIVATE);
int index=sp.getInt("index", 0);
MyUtils.setBackground(this, index, drawable);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.bg1:
sp.edit().putInt("index", 1).commit();
break;
case R.id.bg2:
sp.edit().putInt("index", 2).commit();
break;
default:
sp.edit().putInt("index", 0).commit();
break;
}
int index=sp.getInt("index", 0);
MyUtils.setBackground(this, index, drawable);
return super.onOptionsItemSelected(item);
}
public void open(View v) {
Intent intent=new Intent(this,SecondActivity.class);
startActivity(intent);
}
}
5.第二个界面代码
public class SecondActivity extends Activity {
Drawable drawable;
SharedPreferences sp;
View view;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
view=this.getWindow().getDecorView();//getDecorView 获得window最顶层的View
drawable=view.getBackground();
sp=getSharedPreferences("background", MODE_PRIVATE);
}
@Override
protected void onResume() {
super.onResume();
int index=sp.getInt("index", 0);
MyUtils.setBackground(this, index, drawable);
}
}
6.清单中配置第二个界面
<activity
android:name="cn.lynu.changeactivitybackground.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="cn.lynu.changeactivitybackground.SecondActivity" />
7.效果图