Android片段显示并隐藏

时间:2015-07-23 13:27:38

标签: android fragment

我尝试创建一个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();
    }
}

ProgressFragment预计会附加(添加)到活动一次,并且应该只有一个实例,然后客户端应该只更新其“{1}}。信息或隐藏它。

客户端(活动)中的用法:

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("..")
}

但是它没有按预期工作,有时候进度视图只会在第一次调用时显示,或者甚至不会显示。

我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

  • 请勿将onCreateView设为@Nullable;
  • 使用commitAllowingStateLoss();
  • 使用add()而不只是addToBackStack()。如果要关闭它,只需使用FragmentManager popBackStack()

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