Communication principle between Activities and Fragments

rendering

First, if you want to use fragments on Android 3.0 and below, you must refer to the android-support-v4.jar package

Then you can’t write the activity of the inherited from the activity class, but to inherit the android. Support. The v4. App. FragmentActivity, some of the other parent also have corresponding change.

Since fragment and activity are instantiated as two unrelated objects in the Android implementation mechanism, the connection between them is determined by the activity A member object SupportFragmentManager is used to maintain the Fragment, which is instantiated to SupportFragmentManager in the Activity To register, this action is wrapped in the Fragment object’s onAttach, so you can declare callback interfaces in your fragment when it is a fragment When onAttach is called, instantiate these callback interfaces so that the Fragment can call the activities’ member functions. Of course, the Activity must implements these interfaces, otherwise a ClassCastError is raised!

The callback mechanism for fragments and activities is another perfect example of OOP!

Here is an example:

I split the UI of the Activity into two parts, left and right. The left side is used to place the clicked button (LeftFragment) and the right side is used to place the corresponding information displayed after clicking (RightFragment).

The Activity’s layout file: main.xml

<? The XML version = "1.0" encoding = "utf-8"? > <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" tools:context=".MainActivity"> <LinearLayout android:id="@+id/left_layout" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="2" android:orientation="vertical" /> <LinearLayout android:id="@+id/right_layout" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="8" android:orientation="vertical"/> </LinearLayout>Copy the code

The LeftFragment layout: fragment_left.xml

<? The XML version = "1.0" encoding = "utf-8"? > <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" tools:context=".MainActivity"> <LinearLayout android:id="@+id/left_layout" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="2" android:orientation="vertical" /> <LinearLayout android:id="@+id/right_layout" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="8" android:orientation="vertical"/> </LinearLayout>Copy the code

RightFragment layout:fragment_right.xml

  • I need to say a little bit about constraint layoutConstraintLayoutIt’s for screen adaptation and if you use other layouts it will affect the text display of the TextView
  • Simply put, the width of each line of text is not even!
<? The XML version = "1.0" encoding = "utf-8"? > <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/right_show_message" android:layout_width="0dp" android:layout_height="0dp" android:background="@android:color/holo_blue_dark" android:textColor="@android:color/white" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </android.support.constraint.ConstraintLayout>Copy the code

The above are the layout files of two Fragments and one Activity. Let’s look at their Java files

MainActivity:

Public class MainActivity extends AppCompatActivity implements leftFragment. MyListener {/** * get the control that displays information in RightFragment */ private TextView showMessageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.e("TAG", "Activity--->onCreate"); FragmentManager manager = getSupportFragmentManager(); FragmentTransaction ft = manager.beginTransaction(); // Dynamically add Fragment RightFragment RightFragment = new RightFragment(); LeftFragment leftFragment = new LeftFragment(); ft.add(R.id.left_layout, leftFragment, "leftFragment"); ft.add(R.id.right_layout, rightFragment, "rightFragment"); ft.commit(); } /** * Implement MyListener to make the RightFragment display the information on the first page of the LeftFragment when clicking on the second page. * * @param index */ public void showMessage(int index) {if (index == 1) { showMessageView.setText(R.string.first_page); } if (index == 2) { showMessageView.setText(R.string.second_page); } if (index == 3) { showMessageView.setText(R.string.third_page); } } @Override protected void onResume() { super.onResume(); Log.e("TAG", "Activity--->onResume"); showMessageView = findViewById(R.id.right_show_message); }}Copy the code

LeftFragment:

public class LeftFragment extends Fragment { private MyListener myListener; private Button firstButton; private Button secondButton; private Button thirdButton; /** * Fragment called when it is an Activity for the first time, Public void onAttach(context context) {super.onattach (context); Log.e("TAG", "LeftFragment--->onAttach"); myListener = (MyListener) context; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { Log.e("TAG", "LeftFragment--->onCreate"); super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { Log.e("TAG", "LeftFragment--->onCreateView"); return inflater.inflate(R.layout.fragment_left, container, false); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Log.e("TAG", "LeftFragment--->onActivityCreated"); } @Override public void onResume() { super.onResume(); Log.e("TAG", "LeftFragment--->onResume"); firstButton = getActivity().findViewById(R.id.first_button); secondButton = getActivity().findViewById(R.id.second_button); thirdButton = getActivity().findViewById(R.id.third_button); MyButtonClickListener clickListener = new MyButtonClickListener(); firstButton.setOnClickListener(clickListener); secondButton.setOnClickListener(clickListener); thirdButton.setOnClickListener(clickListener); } public interface MyListener {void showMessage(int index);} public interface MyListener {void showMessage(int index); / / class MyButtonClickListener implements view.onClickListener {@override public void onClick(View);  { Button button = (Button) view; if (button == firstButton) { myListener.showMessage(1); } if (button == secondButton) { myListener.showMessage(2); } if (button == thirdButton) { myListener.showMessage(3); }}}}Copy the code

RightFragment:

public class RightFragment extends Fragment { @Override public void onCreate(@Nullable Bundle savedInstanceState) { Log.e("TAG", "RightFragment--->onCreate"); super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { Log.e("TAG", "RightFragment--->onCreateView"); return inflater.inflate(R.layout.fragment_right, container, false); }}Copy the code

Note:

Relationship between Fragment life cycle and Activity life cycle. To dynamically generate a Fragment in an Activity, the Activity calls onCreate() first.

Method, but there is no component loaded into the Fragment yet. The Activity is retrieved when the Fragment calls its onCreateView() method

Components in fragments

The key here is that the Fragment has an interface and a reference to that interface, and that interface needs the Activity to implement it. When the Fragment calls the onAttach(Context Context) method, it passes the activity to the interface reference so that it can interact with the activity.

Share with you

I want to work my way up

Fly forward on the blades at the highest point

Let the wind blow dry tears and sweat

I want to work my way up

Waiting for the sun to watch its face

Little days have big dreams

I have my day

Let the wind blow dry tears and sweat

One day I will have my day