Fragment的用法

active_main.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     xmlns:app="http://schemas.android.com/apk/res-auto"
 4     xmlns:tools="http://schemas.android.com/tools"
 5     android:layout_width="match_parent"
 6     android:layout_height="match_parent"
 7     tools:context=".ActivityMain">
 8     <Button
 9         android:id="@+id/bt_frag1"
10         android:layout_width="100dp"
11         android:layout_height="wrap_content"
12         android:onClick="actionShowFrag1"
13         />
14     <Button
15         android:id="@+id/bt_frag2"
16         android:layout_width="100dp"
17         android:layout_height="wrap_content"
18         app:layout_constraintLeft_toRightOf="@id/bt_frag1"
19         android:onClick="actionShowFrag2"
20         />
21     <FrameLayout
22         android:id="@+id/frame_frag"
23         android:layout_width="match_parent"
24         android:layout_height="0dp"
25         android:layout_weight="1"
26         app:layout_constraintTop_toBottomOf="@id/bt_frag1"/>
27 
28 </android.support.constraint.ConstraintLayout>

fragment_one.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     xmlns:tools="http://schemas.android.com/tools"
 4     android:layout_width="match_parent"
 5     android:layout_height="match_parent"
 6     tools:context=".FragmentOne">
 7 
 8     <!-- TODO: Update blank fragment layout -->
 9     <TextView
10         android:layout_width="match_parent"
11         android:layout_height="match_parent"
12         android:text="one" />
13 
14 </FrameLayout>

fragment_two.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     xmlns:tools="http://schemas.android.com/tools"
 4     android:layout_width="match_parent"
 5     android:layout_height="match_parent"
 6     tools:context=".FragmentTwo">
 7 
 8     <!-- TODO: Update blank fragment layout -->
 9     <TextView
10         android:layout_width="match_parent"
11         android:layout_height="match_parent"
12         android:text="two" />
13 
14 </FrameLayout>

FragmentOne.java

  1 package com.code369.app_frag;
  2 
  3 import android.content.Context;
  4 import android.net.Uri;
  5 import android.os.Bundle;
  6 import android.support.v4.app.Fragment;
  7 import android.view.LayoutInflater;
  8 import android.view.View;
  9 import android.view.ViewGroup;
 10 
 11 
 12 /**
 13  * A simple {@link Fragment} subclass.
 14  * Activities that contain this fragment must implement the
 15  * {@link FragmentOne.OnFragmentInteractionListener} interface
 16  * to handle interaction events.
 17  * Use the {@link FragmentOne#newInstance} factory method to
 18  * create an instance of this fragment.
 19  */
 20 public class FragmentOne extends Fragment {
 21     // TODO: Rename parameter arguments, choose names that match
 22     // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
 23     private static final String ARG_PARAM1 = "param1";
 24     private static final String ARG_PARAM2 = "param2";
 25 
 26     // TODO: Rename and change types of parameters
 27     private String mParam1;
 28     private String mParam2;
 29 
 30     private OnFragmentInteractionListener mListener;
 31 
 32     public FragmentOne() {
 33         // Required empty public constructor
 34     }
 35 
 36     /**
 37      * Use this factory method to create a new instance of
 38      * this fragment using the provided parameters.
 39      *
 40      * @param param1 Parameter 1.
 41      * @param param2 Parameter 2.
 42      * @return A new instance of fragment FragmentOne.
 43      */
 44     // TODO: Rename and change types and number of parameters
 45     public static FragmentOne newInstance(String param1, String param2) {
 46         FragmentOne fragment = new FragmentOne();
 47         Bundle args = new Bundle();
 48         args.putString(ARG_PARAM1, param1);
 49         args.putString(ARG_PARAM2, param2);
 50         fragment.setArguments(args);
 51         return fragment;
 52     }
 53 
 54     @Override
 55     public void onCreate(Bundle savedInstanceState) {
 56         super.onCreate(savedInstanceState);
 57         if (getArguments() != null) {
 58             mParam1 = getArguments().getString(ARG_PARAM1);
 59             mParam2 = getArguments().getString(ARG_PARAM2);
 60         }
 61     }
 62 
 63     @Override
 64     public View onCreateView(LayoutInflater inflater, ViewGroup container,
 65                              Bundle savedInstanceState) {
 66         // Inflate the layout for this fragment
 67         return inflater.inflate(R.layout.fragment_one, container, false);
 68     }
 69 
 70     // TODO: Rename method, update argument and hook method into UI event
 71     public void onButtonPressed(Uri uri) {
 72         if (mListener != null) {
 73             mListener.onFragmentInteraction(uri);
 74         }
 75     }
 76 
 77     @Override
 78     public void onAttach(Context context) {
 79         super.onAttach(context);
 80         if (context instanceof OnFragmentInteractionListener) {
 81             mListener = (OnFragmentInteractionListener) context;
 82         } else {
 83             throw new RuntimeException(context.toString()
 84                     + " must implement OnFragmentInteractionListener");
 85         }
 86     }
 87 
 88     @Override
 89     public void onDetach() {
 90         super.onDetach();
 91         mListener = null;
 92     }
 93 
 94     /**
 95      * This interface must be implemented by activities that contain this
 96      * fragment to allow an interaction in this fragment to be communicated
 97      * to the activity and potentially other fragments contained in that
 98      * activity.
 99      * <p>
100      * See the Android Training lesson <a href=
101      * "http://developer.android.com/training/basics/fragments/communicating.html"
102      * >Communicating with Other Fragments</a> for more information.
103      */
104     public interface OnFragmentInteractionListener {
105         // TODO: Update argument type and name
106         void onFragmentInteraction(Uri uri);
107     }
108 }

FragmentTwo.java

  1 package com.code369.app_frag;
  2 
  3 import android.content.Context;
  4 import android.net.Uri;
  5 import android.os.Bundle;
  6 import android.support.v4.app.Fragment;
  7 import android.view.LayoutInflater;
  8 import android.view.View;
  9 import android.view.ViewGroup;
 10 
 11 
 12 /**
 13  * A simple {@link Fragment} subclass.
 14  * Activities that contain this fragment must implement the
 15  * {@link FragmentTwo.OnFragmentInteractionListener} interface
 16  * to handle interaction events.
 17  * Use the {@link FragmentTwo#newInstance} factory method to
 18  * create an instance of this fragment.
 19  */
 20 public class FragmentTwo extends Fragment {
 21     // TODO: Rename parameter arguments, choose names that match
 22     // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
 23     private static final String ARG_PARAM1 = "param1";
 24     private static final String ARG_PARAM2 = "param2";
 25 
 26     // TODO: Rename and change types of parameters
 27     private String mParam1;
 28     private String mParam2;
 29 
 30     private OnFragmentInteractionListener mListener;
 31 
 32     public FragmentTwo() {
 33         // Required empty public constructor
 34     }
 35 
 36     /**
 37      * Use this factory method to create a new instance of
 38      * this fragment using the provided parameters.
 39      *
 40      * @param param1 Parameter 1.
 41      * @param param2 Parameter 2.
 42      * @return A new instance of fragment FragmentTwo.
 43      */
 44     // TODO: Rename and change types and number of parameters
 45     public static FragmentTwo newInstance(String param1, String param2) {
 46         FragmentTwo fragment = new FragmentTwo();
 47         Bundle args = new Bundle();
 48         args.putString(ARG_PARAM1, param1);
 49         args.putString(ARG_PARAM2, param2);
 50         fragment.setArguments(args);
 51         return fragment;
 52     }
 53 
 54     @Override
 55     public void onCreate(Bundle savedInstanceState) {
 56         super.onCreate(savedInstanceState);
 57         if (getArguments() != null) {
 58             mParam1 = getArguments().getString(ARG_PARAM1);
 59             mParam2 = getArguments().getString(ARG_PARAM2);
 60         }
 61     }
 62 
 63     @Override
 64     public View onCreateView(LayoutInflater inflater, ViewGroup container,
 65                              Bundle savedInstanceState) {
 66         // Inflate the layout for this fragment
 67         return inflater.inflate(R.layout.fragment_two, container, false);
 68     }
 69 
 70     // TODO: Rename method, update argument and hook method into UI event
 71     public void onButtonPressed(Uri uri) {
 72         if (mListener != null) {
 73             mListener.onFragmentInteraction(uri);
 74         }
 75     }
 76 
 77     @Override
 78     public void onAttach(Context context) {
 79         super.onAttach(context);
 80         if (context instanceof OnFragmentInteractionListener) {
 81             mListener = (OnFragmentInteractionListener) context;
 82         } else {
 83             throw new RuntimeException(context.toString()
 84                     + " must implement OnFragmentInteractionListener");
 85         }
 86     }
 87 
 88     @Override
 89     public void onDetach() {
 90         super.onDetach();
 91         mListener = null;
 92     }
 93 
 94     /**
 95      * This interface must be implemented by activities that contain this
 96      * fragment to allow an interaction in this fragment to be communicated
 97      * to the activity and potentially other fragments contained in that
 98      * activity.
 99      * <p>
100      * See the Android Training lesson <a href=
101      * "http://developer.android.com/training/basics/fragments/communicating.html"
102      * >Communicating with Other Fragments</a> for more information.
103      */
104     public interface OnFragmentInteractionListener {
105         // TODO: Update argument type and name
106         void onFragmentInteraction(Uri uri);
107     }
108 }

ActivityMain.java

 1 package com.code369.app_frag;
 2 
 3 import android.net.Uri;
 4 import android.support.v4.app.Fragment;
 5 import android.support.v4.app.FragmentManager;
 6 import android.support.v4.app.FragmentTransaction;
 7 import android.support.v7.app.AppCompatActivity;
 8 import android.os.Bundle;
 9 import android.view.View;
10 
11 public class ActivityMain extends AppCompatActivity implements FragmentOne.OnFragmentInteractionListener,
12 FragmentTwo.OnFragmentInteractionListener{
13 
14     private Fragment mFragOne;
15     private Fragment mFragTwo;
16     private FragmentManager mFragMgr;
17     @Override
18     protected void onCreate(Bundle savedInstanceState) {
19         super.onCreate(savedInstanceState);
20         setContentView(R.layout.activity_main);
21 
22         mFragMgr = getSupportFragmentManager();
23         mFragOne = FragmentOne.newInstance("1", "2");
24         mFragTwo = FragmentTwo.newInstance("3", "4");
25 
26         FragmentTransaction trans = mFragMgr.beginTransaction();
27         trans.add(R.id.frame_frag, mFragOne);
28         trans.add(R.id.frame_frag, mFragTwo);
29         trans.commit();
30     }
31 
32     private void ShowFragment(Fragment frag)
33     {
34         FragmentTransaction trans = mFragMgr.beginTransaction();
35         trans.show(frag);
36         trans.commit();
37     }
38 
39     private void HideAllFragement(){
40         FragmentTransaction trans = mFragMgr.beginTransaction();
41         if(mFragOne != null){
42             trans.hide(mFragOne);
43         }
44         if(mFragTwo != null){
45             trans.hide(mFragTwo);
46         }
47         trans.commit();
48     }
49 
50     public void actionShowFrag1(View view)
51     {
52         HideAllFragement();
53         ShowFragment(mFragOne);
54     }
55 
56     public void actionShowFrag2(View view)
57     {
58         HideAllFragement();
59         ShowFragment(mFragTwo);
60     }
61 
62     @Override
63     public void onFragmentInteraction(Uri uri) {
64         //留空即可
65     }
66 }
原文地址:https://www.cnblogs.com/CipherLab/p/14098168.html