无法打开第二个片段

时间:2016-05-24 06:46:20

标签: android android-fragments

点击Button我试图打开第二个片段(YourResultFragment.java), 我有很多,但不知道它为什么不起作用,这是我正在使用的代码

public class KnowYourBodyFragment extends Fragment {


    public KnowYourBodyFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_know_your_body, container, false);




        Button button = (Button)rootView.findViewById(R.id.button2);
        button.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {

                Fragment mFragment = new YourResultFragment(); 
                 getActivity().getSupportFragmentManager().beginTransaction()
                            .replace(R.id.know_your_body_container, mFragment ).commit();
            }
        }); 

        // Inflate the layout for this fragment
        return rootView;
    }

1 个答案:

答案 0 :(得分:1)

  

使用此尝试将其替换为 Default Container android.R.id.content

Button button = (Button)rootView.findViewById(R.id.button2);
button.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            Fragment newFragment = new YourResultFragment();
            FragmentTransaction transaction = getFragmentManager()
                    .beginTransaction();

            // Replace whatever is in the fragment_container view with this
            // fragment,
            // and add the transaction to the back stack
            transaction.replace(android.R.id.content, newFragment);
            transaction.addToBackStack("tag");

            // Commit the transaction
            transaction.commitAllowingStateLoss();

        }
    });
  

什么是transaction.addToBackStack("tag")

将此事务添加到后台堆栈。这意味着事务将在提交后被记住,并在稍后从堆栈中弹出时将反转其操作。