我有一个简单的程序,可以从活动B中更改活动A的背景。 当您更改背景时,您需要刷新活动A以便更改背景,在查看stackoverflow之后,最简单的方法就是调用recreate()。
我不确定我是在调用错误还是在错误的区域,但最终发生的事情是,当应用程序运行并最终崩溃时,它会循环以下错误 -
02-01 13:23:53.358 17302-17302/com.package.www.randomapp E/ViewRootImpl: sendUserActionEvent() mView == null
这是活动A的代码
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainmenu);
backgroundChanger();
recreate();
}
public void backgroundChanger(){
SharedPreferences sharedGradients = getSharedPreferences("gradientInfo", Context.MODE_PRIVATE);
int backgroundGrad = sharedGradients.getInt("backgroundGradient", 0);
if (backgroundGrad == 0){
MMBackground.setBackgroundResource(R.drawable.blackgreengradiant);
}
if (backgroundGrad == 1){
MMBackground.setBackgroundResource(R.drawable.blueblackgradiant);
}
if (backgroundGrad == 2){
MMBackground.setBackgroundResource(R.drawable.goldblackgradiant);
}
和活动B
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_options_menu);
variableHandler();
}
public void variableHandler() {
MainMenuBackgroundBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
final SharedPreferences[] sharedGradients = {getSharedPreferences("gradientInfo", Context.MODE_PRIVATE)};
final SharedPreferences.Editor[] editor1 = {sharedGradients[0].edit()};
final SharedPreferences[] sharedBoolean = {getSharedPreferences("binaryPoint", Context.MODE_PRIVATE)};
final SharedPreferences.Editor[] editorBinary = {sharedBoolean[0].edit()};
final PopupMenu popup = new PopupMenu(getApplicationContext(), v);
popup.inflate(R.menu.menu_background_gradiant_setter);
popup.show();
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.item1:
Toast.makeText(OptionsMenu.this, "Blue and black gradient", Toast.LENGTH_SHORT).show();
editorBinary[0] = sharedBoolean[0].edit();
editorBinary[0].putInt("binaryPoint", 1);
editor1[0] = sharedGradients[0].edit();
editor1[0].putInt("backgroundGradient", 1);
editor1[0].apply();
return true;
case R.id.item2:
Toast.makeText(OptionsMenu.this, "Gold and black gradient", Toast.LENGTH_SHORT).show();
editorBinary[0] = sharedBoolean[0].edit();
editorBinary[0].putInt("binaryPoint", 1);
editor1[0] = sharedGradients[0].edit();
editor1[0].putInt("backgroundGradient", 2);
editor1[0].apply();
return true;
}
}
答案 0 :(得分:2)
问题是你在Activity的recreate()
方法中调用onCreate()
而没有任何会产生无限循环的条件。保留一个变量来跟踪是否重新创建活动。
private static boolean alreadyRecreated = false;
//You can add some extra conditions here if you want.
if(!alreadyRecreated){
recreate();
alreadyRecreated = true;
}
答案 1 :(得分:0)
recreate();
会导致您的活动被重新创建。
即onCreate被调用。因为,你在onCreate方法中添加了recreate();
,它会运行到无限循环并崩溃。