Android 动态修改Activity主题
2016-12-03 本文已影响45人
蜂鸟之歌
public class MainActivity extends Activity {
/** 系统自带主题 */
private static final int DEFAULT_THEME = 0;
/** 绿色 */
private static final int GREEN_THEME = 1;
/** 橘黄色 */
private static final int ORANGE_THEME = 2;
public static int current_theme = -1;
@Override
protected void onCreate(Bundle savedInstanceState) {
if (current_theme!= -1){
this.setTheme(current_theme);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.bt_theme).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showChooseDialog();
}
});
}
public void changeTheme(int index) {
switch (index) {
case DEFAULT_THEME:
current_theme = R.style.DefaultTheme;
break;
case GREEN_THEME:
current_theme = R.style.GreenTheme;
break;
case ORANGE_THEME:
current_theme = R.style.OrangeTheme;
break;
default:
break;
}
}
protected void reload() {
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
private int mCurrentWhich = 0;
private int mTempWhich;
private void showChooseDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("选择主题");
final String[] items = new String[] {"系统自带1","绿色","橘黄色" };
//显示单选框,参1:单选字符串数组;参2:当前默认选中的位置;参3:选中监听
builder.setSingleChoiceItems(items, mCurrentWhich,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mTempWhich = which;
Toast.makeText(MainActivity.this, items[which], Toast.LENGTH_SHORT).show();
}
});
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mCurrentWhich = mTempWhich;
changeTheme(mCurrentWhich);
reload();
}
});
builder.setNegativeButton("取消", null);
builder.show();
}
}