从同一个按钮打开和关闭片段?

时间:2017-01-09 18:51:30

标签: android android-fragments

我的活动有碎片。现在我有按钮打开片段。我想知道如何使用相同的按钮打开和关闭片段? 我的代码是:

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) {

    }
}

1 个答案:

答案 0 :(得分: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();
    }
}