简体   繁体   English

如何检查片段是否在Activity OnBackpressed中可见

[英]How to check fragment is visible in Activity OnBackpressed

How to check fragment is visible in Activity OnBackpressed 如何检查片段是否在Activity OnBackpressed中可见

I want to check when user click back button in Searchfragment I want to set OnBackpressed is running ,but if user click back button in OtherFragment I want to set OnBackpressed is not running. 我想检查用户要设置OnBackpressed的Searchfragment中的单击后退按钮何时在运行,但是如果用户单击要设置OnBackpressed的OtherFragment中的后退按钮没有在运行。

and I try this in Activity is not work 我尝试在活动中不起作用

 btn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SearchFragment searchFragment = new SearchFragment();
                if (searchFragment.isVisible()){
                    onBackPressed();
                }

            }
        });

thanks for your help! 谢谢你的帮助!

First of all, when you declare something like this: 首先,当您声明如下内容时:

SearchFragment searchFragment = new SearchFragment();

And then call 然后打电话

searchFragment.isVisible()

This will obviously return false since you didnt even add it to the container. 显然,这将返回false因为您甚至没有将其添加到容器中。 What you need to do is to retrieve the fragment instance that you already added and check it's state. 您需要做的是检索已经添加的片段实例并检查其状态。

I have once tried to use the method isVisible() but it is not entirely accurate, at least not for my case. 我曾经尝试使用isVisible()方法,但它并不完全准确,至少对于我而言并非如此。 What I came up with is to check the top fragment in the container as follow: 我想到的是按照以下步骤检查容器中的顶部片段:

Fragment fragment = getActivity().getSupportFragmentManager().findFragmentById(R.id.fragment_container);
if(fragment instance of SearchFragment) //means your visible fragment is the SearchFragment
    onBackPressed();

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM