1、在res/values/styles.xml里定义好主题。
2、在Acticity的setContentView()方法之前调用 setTheme(R.style.myTheme)方法。
3、利用recreate()方法重建Activity即可。
举个例子,我们用一个boolean值来控制两种主题:AppTheme和YellowTheme,由于要重建主题,所以这个boolean需要是static的,或者做持久化处理。当然也可以利用ViewModel来存储这个boolean值。
MainViewModel:
public class MainViewModel extends ViewModel {
private boolean mYellowTheme = false;
public void changeThemeTag() {
mYellowTheme = !mYellowTheme;
}
public boolean isYellowTheme() {
return mYellowTheme;
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
private static final String LOG_TAG = "MainActivityLog";
private Button mButton;
private MainViewModel mViewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mViewModel = ViewModelProviders.of(this).get(MainViewModel.class);
changeTheme();
setContentView(R.layout.activity_main);
mButton = findViewById(R.id.button);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mViewModel.changeThemeTag();
recreate();
}
});
}
private void changeTheme() {
if (mViewModel.isYellowTheme()) {
setTheme(R.style.YellowTheme);
} else {
setTheme(R.style.AppTheme);
}
}
}