检查添加的Android片段中的onPause,onResume和onDestroy

问题描述 投票:0回答:2

当我添加片段并使用以下代码从Fragment1转到Fragment2时:

Bundle bundle = new Bundle();
                    bundle.putString(Constants.USER_NAME, item_username);
                    AppCompatActivity activity = (AppCompatActivity) view.getContext();
                    Fragment myFragment = new Fragment2();
                    myFragment.setArguments(bundle);
                    activity.getSupportFragmentManager().beginTransaction().add(R.id.frame_fragment_containers, myFragment).addToBackStack(null).commit();

当我从Fragment2回来时,我无法检查Fragment1中的onPause和onDestroy以及Fragment1中的onResume。我想通过添加来做到这一点,并且不要使用替换。请帮我。谢谢

android fragment
2个回答
0
投票

onPause()onResume()用于活动。我认为您应该尝试通过以下方式设置片段的可见性:

public class YourFragment extends Fragment {
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
           // Do Something onResume
        }
        else {
           // Do Something onPause
        }
    }
}

0
投票

您需要使用replace()而不是add()才能将fragment1添加到后堆栈中并显示fragment2

© www.soinside.com 2019 - 2024. All rights reserved.