简体   繁体   English

OnResume() 在 MainActivity 中导致无限循环

[英]OnResume() causing infinite loop in MainActivity

I've recently added the OnResume method to my main activity, however, after doing this, my app is now stuck in an infinite loop because OnResume is being called repeatedly, but I don't know why.我最近在我的主要活动中添加了 OnResume 方法,但是,在这样做之后,我的应用程序现在陷入无限循环,因为 OnResume 被重复调用,但我不知道为什么。

Any ideas what it is about my MainActivity code that's causing the OnResume method to be called repeatedly?任何想法是什么我的 MainActivity 代码导致 OnResume 方法被重复调用? Or is there a way in Android Studio I can trace back to see where the call originates from?或者在 Android Studio 中是否有一种方法可以追溯以查看调用的来源?

For reference, the reason I want to call recreate in the OnResume method is that the user can change the active theme in another activity, so when I come back to MainActivity I want it to pick up the theme change.作为参考,我想在 OnResume 方法中调用 recreate 的原因是用户可以在另一个活动中更改活动主题,所以当我回到 MainActivity 时,我希望它选择主题更改。

public class MainActivity extends AppCompatActivity {

    Toolbar toolbar;
    TabLayout tabLayout;
    static int errorDelay = 2000;
    ViewPager viewPager;
    PageAdapter pageAdapter;
    TabItem tabAveSpeed;
    TabItem tabDistance;
    TabItem tabTime;



    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (v instanceof EditText) {
                Rect outRect = new Rect();
                v.getGlobalVisibleRect(outRect);
                if (!outRect.contains((int) event.getRawX(), (int) event.getRawY())) {
                    v.clearFocus();
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
        }
        return super.dispatchTouchEvent(event);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        if (!PrefUtil.getBool(this, "usedBefore")) {
            PrefUtil.saveInt(this, "distanceSpinnerPref", 0);
            PrefUtil.saveBool(this, "usedBefore", true);
            PrefUtil.saveString(this, "activeThemeColour", "Grey");
        }

        String colour = PrefUtil.getString(this, "activeThemeColour");

        switch (colour) {
            case "Green":
                setTheme(R.style.AppTheme_Green);
                break;
            case "Grey":
                setTheme(R.style.AppTheme_Grey);
                break;
            default:
                setTheme(R.style.AppTheme_Grey);
                break;
        }


        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        toolbar = findViewById(R.id.toolbar);
        toolbar.setTitle(getResources().getString(R.string.app_name));
        setSupportActionBar(toolbar);

        tabLayout = findViewById(R.id.tabMenu);
        tabAveSpeed = findViewById(R.id.averageSpeedTab);
        tabDistance = findViewById(R.id.distanceTab);
        tabTime = findViewById(R.id.timeTab);
        viewPager = findViewById(R.id.viewPager);

        pageAdapter = new PageAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
        viewPager.setAdapter(pageAdapter);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));



        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    @Override
    protected void onResume(){
        super.onResume();
        recreate();
    }

    public void updateTabTitle (String newTitle){
        TabLayout tabLayout;
        tabLayout = findViewById(R.id.tabMenu);
        tabLayout.getTabAt(0).setText(newTitle);
    }
}

As others have mentioned, indiscriminately calling recreate() in your onResume() method is going to give you infinite loops.正如其他人所提到的,在您的onResume()方法中不加选择地调用recreate()会给您带来无限循环。

You can probably do something like write a value to SharedPreferences whenever the user changes the theme, and then check that value in your onResume() and only call recreate() if the theme has changed.您可以执行一些操作,例如在用户更改主题时将值写入SharedPreferences ,然后在您的onResume()检查该值,如果主题已更改,则仅调用recreate()

In your other activity, when the user changes the theme, do this:在您的其他活动中,当用户更改主题时,请执行以下操作:

PreferencesManager.getDefaultSharedPreferences(context)
        .edit()
        .putBoolean("theme_changed", true)
        .apply();

And then in your other activity, inside onResume() , do this:然后在您的其他活动中,在onResume() ,执行以下操作:

SharedPreferences prefs = PreferencesManager.getDefaultSharedPreferences(this);

if (prefs.getBoolean("theme_changed", false)) {
    prefs.edit().remove("theme_changed").apply();
    recreate();
}

In this way, you'll only recreate() when there's a reason to do so, and won't loop forever.这样,您只会在有理由这样做时才recreate() ,并且不会永远循环。

Delete recreate();删除recreate(); from this line:从这一行:

@Override
protected void onResume(){
    super.onResume();
    //recreate();  - delete this line
}

You can read here in docs what recreate() do.您可以在文档中阅读recreate()作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 权限请求在OnResume中导致无限循环 - Permission Requests causes infinite loop in OnResume Android:未调用MainActivity中的onResume - Android: onResume in MainActivity not called setState() 在 flutter 中导致无限循环 - setState() causing infinite loop in flutter 服务运行http命令导致无限循环 - service to run http command causing infinite loop Account.setPassword导致SyncAdapter无限循环 - Account.setPassword causing SyncAdapter infinite loop onResume在启动时导致问题 - onResume causing problems on start up Android:在onCreate中启动一个intent会导致无限循环/崩溃 - Android: Starting an intent inside of onCreate is causing an infinite loop / crash 待定意图导致mainactivity重新加载,为什么? - Pending Intent Causing mainactivity to reload, why is that? 如何在删除导致无限循环的对象时修复基于Android的Firebase错误? - How to fix android based Firebase error while deleting objects causing an infinite loop? React Native:使用pop()或goBack()时出现性能问题,导致无限循环。 但是使用`reset`就可以了 - React Native: Performance issue when using `pop()` or `goBack()`, causing an infinite loop. But using `reset` is fine
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM