哪种方法可以使用多个片段?

时间:2018-07-31 00:38:54

标签: java android android-layout android-fragments

我有两个片段,分别为SignInFragmentSignUpFragment。首先MainActivity用此代码调用SignInFragment

//MainActivity
if (savedInstanceState == null) {
    signInFragment = new SignInFragment();
    signUpFragment = new SignUpFragment();

    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.add(R.id.frame_holder,signInFragment);
    fragmentTransaction.commit();
}

SignUpFragment中单击注册按钮后,如何呼叫SignInFragment。我对按钮有参考:

//SignInFragment    
Button buttonSignUp = view.findViewById(R.id.button_sign_up);

2 个答案:

答案 0 :(得分:3)

您需要先覆盖onClick注册按钮。

并将此代码放入

      FragmentTransaction fragmentTransaction = 
              getSupportFragmentManager().beginTransaction();
              fragmentTransaction.replace(R.id.frame_holder, signInFragment);
              fragmentTransaction.commit();

并且如sudhanshu-vohra所述,您必须替换,而不是添加frame_holder

答案 1 :(得分:0)

重写它们各自的 onClick()方法以响应按钮上的单击事件,并以以下方式编写代码以替换片段:

public void onClick(View v) {
    switch(v.getId()){
     case R.id.button_sign_up:
      FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.frame_holder, signInFragment);
            fragmentTransaction.commit();
    }
}

注意:当第二次(或任何连续时间)添加任何片段时,您需要替换该片段而不是添加该片段,因为添加只会覆盖其他片段在第一个片段上。有关更多信息,请参见this answer