2017-01-09 64 views
0

我有活動有片段。現在我有按鈕打開片段。我想知道如何使用相同的按鈕打開和關閉片段? 我的代碼是:從同一個按鈕打開和關閉片段?

public class MainActivity extends AppCompatActivity { 
    FragmentTransaction fTrans; 
    Button reg; 
    @Override 
     protected void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.activity_main); 
      reg = (Button) findViewById(R.id.reg); 
      frag1 = new Fragment1(); 
     } 
     public void openFragment(View v){ 
      fTrans = getFragmentManager().beginTransaction(); 
      fTrans.add(R.id.frgmCont, frag1); 
      fTrans.commit(); 
     } 
    } 

MainActivity的XML文件。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:id="@+id/activity_main" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context="com.example.user.myapplication5.MainActivity"> 
<Button 
    android:id="@+id/reg" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:text="Registration" 
    android:background="@drawable/add_btn" 
    android:layout_margin="10dp" 
    android:onClick="openFragment" 
    /> 

    <FrameLayout 
     android:id="@+id/frgmCont" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent"> 
    </FrameLayout> 
</LinearLayout> 

這裏是片段:

public class Fragment1 extends Fragment { 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     return inflater.inflate(R.layout.fragment1, null); 

    } 
    public void onViewCreated(View view, Bundle savedInstanceState) { 

    } 
} 

回答

0

改變你的活動代碼這個

public class MainActivity extends AppCompatActivity { 
FragmentTransaction fTrans; 
Button reg; 
boolean flag = false; 
@Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     reg = (Button) findViewById(R.id.reg); 
     frag1 = new Fragment1(); 
    } 
    public void openFragment(View v){ 
     fTrans = getFragmentManager().beginTransaction(); 
     if(flag) { 
      fTrans.remove(frag1); 
     } else { 
      fTrans.add(R.id.frgmCont, frag1); 
     } 
     flag = !flag; 
     fTrans.commit(); 
    } 
} 
+0

謝謝你非常匹配。 – KeitL

+0

不客氣@KeitL –