简体   繁体   English

Android片段显示和隐藏

[英]Android fragment show and hide

I tried to create a ProgressFragment to be used in the whole application: 我试图创建一个ProgressFragment以在整个应用程序中使用:

public class ProgressFragment extends Fragment {
    private static final String KEY = "info";
    private CustomProgressView mProgress;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(...);
        mProgress = (CustomProgressView) root.findViewById(...);
        mProgress.start();
        if (getArguments() != null) {
            mProgress.setText(getArguments().getString(KEY, ""));
        }
        return root;
    }

    public void setInformation(String text) {
        if (mProgress != null) {
            if (this.isHidden()) {
                show(getActivity().getSupportFragmentManager());
            }
            mProgress.setText(text);
        } else {
            Bundle b = new Bundle();
            b.putString(KEY, text);
            setArguments(b);
        }
    }

    public void hide(FragmentManager fm) {
        FragmentTransaction ft = fm.beginTransaction();
        ft.hide(this);
        ft.commit();
    }
    private void show(FragmentManager fm) {
        FragmentTransaction ft = fm.beginTransaction();
        ft.show(this);
        ft.commit();
    }
}

The ProgressFragment is expected to attached(added) to the activity once, and there should be only one instance, then the client should only update its' information or hide it. ProgressFragment应该一次附加(添加)到活动,并且应该只有一个实例,然后客户端应仅更新其信息或隐藏它。

Usage in client(activity): 客户端使用情况(活动):

class MainActivity...{
    ProgressFragment mFragment;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mFragment = ProgressFragment.newInstance(null);
        FragmentTransaction fs = getSupportFragmentManager().beginTransaction();
        fs.add(id, mFragment);
        fs.commit();
    }

    //close the progress
    mFragment.hide()


    //show the progress 
    mFragment.setInformation("..")
}

However it does not worked as expected, sometime the progress view will show only at the first call or it does not even show. 但是,它不能按预期工作,有时进度视图将仅在首次调用时显示,甚至不显示。

Did I miss anything? 我有想念吗?

  • Don't set your onCreateView as @Nullable ; 不要将onCreateView设置为@Nullable
  • Use commitAllowingStateLoss() ; 使用commitAllowingStateLoss() ;
  • Instead of just add() , use addToBackStack() . 不仅add()使用add() ,还可以使用addToBackStack() When you want to close it, just use the FragmentManager popBackStack() : 当您要关闭它时,只需使用FragmentManager popBackStack()

     getActivity().getSupportFragmentManager().popBackStack(); 

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

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