Android Getting Started Tutorial | Fragment (Loading Method and Communication)

Insert image description here

Fragment loading method

There are two ways to load

  • Register in xml file
  • Load in Java code

Register in xml :

For example, fragment_demo.xmldefined in

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <fragment
        android:id="@+id/main_fragment_up"
        android:name="com.rust.fragment.FirstFragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <fragment
        android:id="@+id/main_fragment_bottom"
        android:name="com.rust.fragment.SecondFragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />
</LinearLayout>

com.rust.fragment.SecondFragmentThat is, the Fragment subclass SecondFragment.javaoverrides onCreateViewthe method and returns the defined view.

Just load it directly in the activity

setContentView(R.layout.fragment_demo);

Loading in Java code

① Prepare the Fragment xml layout file ② Create a new class, inherited from Fragment; find the Fragment layout file in this class ③ Use FragmentManager in Activity to operate Fragment ④ Don’t forget to commit

First customize a layout filefragment_first.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#0011ff" >
<!-- <Button
    android:id="@+id/btn_fragment1_1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/btn_fragment1"
    android:textSize="16sp"
       />
<EditText
    /> -->
</LinearLayout>

Create a new class FirstFragment.javathat inherits from Fragment. Copy onCreateViewmethod. In onCreateViewthe method, you can operate the controls on the Fragment.

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
    
    
        View rootView = inflater.inflate(R.layout.fragment_first, container,false);
//    fragment_first是自定义好的布局
//    如果此Fragment上放了控件,比如Button,Edittext等。可以在这里定义动作
  btn_fragment1_send = (Button) rootView.findViewById(R.id.btn_fragment1_1);
//...
        return rootView;
    }

Prepare a position for Fragment, such as activity_main.xmlusing Framelayout to occupy the position.

    <FrameLayout
        android:id="@+id/layout_container1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="4" >
    </FrameLayout>

In MainActivity.java, first get the FragmentManager and then get the FragmentTransaction. Operations such as addition and deletion of Fragment are completed by FragmentTransaction.

f1 = new FirstFragment();    //    获取实例
f2 = new SecondFragment();    //
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.layout_container1,f1);    //    添加
fragmentTransaction.replace(R.id.layout_container1,f1);    //    替换
// 或者也可以写成
fragmentTransaction.replace(R.id.layout_container1,new FirstFragment());
//              fragmentTransaction.addToBackStack(null);   //添加到返回栈,这样按返回键的时候能返回已添加的fragment
fragmentTransaction.commit();    //别忘了commit
//    移除操作 getFragmentManager().beginTransaction().remove(f1).commit();

Compared with registration in xml, code loading is more flexible. Personally, I prefer dynamic loading.

Cooperation between Fragment and Activity

Activity is executed first onResume, and then the onResumecurrent Fragment is executed. The current Fragment is replaced, and when it is replaced again, some states are not reinitialized. When replacing is executed, the Fragment's declaration cycle will be run again. A safe approach is onCreateViewto initialize the necessary variables in . For example, reset some status values. Special attention is required when switching between multiple Fragments.

Communication between Fragments

In the Fragment's java file, you can use getActivity()to get the activity that calls it, and then find another Fragment to communicate

getActivity().getFragmentManager().findFragmentById(R.id.fragment_list);

However, this coupling is too high and is inconvenient for subsequent modification operations.

The communication between a Fragment and its attached Activity should be completed by the Activity; it cannot be direct communication between multiple Fragments.

Communication method between Fragment and its attached Activity:
  • Define an interface in the Fragment that initiates the event, and declare your methods in the interface
  • Require Activity to implement this interface in the onAttach method
  • Implement this method in Activity

For example, two Fragments are arranged in an activity, and the communication between them depends on the activity.

Code:ListStoreActivity.java NewItemFragment.java ListStoreFragment.java

The layout file is:liststore.xml new_item_fragment.xml

Prepare layout file :

liststore.xmlUse LinearLayout to place 2 fragments, pointing to 2 Fragment files respectively. new_item_fragment.xmlPlace an EditText and a button side by side.

ListStoreFragment.javaUse the interface defined earlier

public class ListStoreFragment extends ListFragment{
    
    
/// 继承自ListFragment,已经封装好了listview
/// 不需要自己写ListView了
}

NewItemFragment.java

/**
 * 声明一个接口,定义向activity传递的方法
 * 绑定的activity必须实现这个方法
 */
    public interface OnNewItemAddedListener {
    
    
        public void newItemAdded(String content);
    }
    private OnNewItemAddedListener onNewItemAddedListener;
    private Button btnAddItem;
    /*复写onAttach方法*/
    @Override
    public void onAttach(Activity activity) {
    
    
        super.onAttach(activity);
        try {
    
    
            onNewItemAddedListener = (OnNewItemAddedListener) activity;
        } catch (ClassCastException e){
    
    
            throw new ClassCastException(activity.toString() + "must implement OnNewItemAddedListener");
        }
    }

ListStoreActivity.javaLoad the main view liststore.xml;

Two Fragments ListStoreActivitycommunicate through

Obtain the instance of ListStoreFragment in the onCreate method; and override the newItemAdded method and add business logic in it

public class ListStoreActivity extends Activity implements OnNewItemAddedListener{
    
    

    private ArrayList<String> data;
    private ArrayAdapter<String> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.liststore);
        data = new ArrayList<String>();
        // 把data装入adapter中
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
        // ListFragment并不需要再定义一个listview 
        ListStoreFragment listStoreFragment = (ListStoreFragment) getFragmentManager().findFragmentById(R.id.fragment_listview);
        listStoreFragment.setListAdapter(adapter);
    }

    @Override
    public void newItemAdded(String content) {
    
    
        //  复写接口中的方法,业务代码在这里实现
        if(!content.equals("")) {
    
    
            data.add(content);
            adapter.notifyDataSetChanged();
        }
    }
}

The disadvantage of this is that the degree of coupling is very high

Several communication methods between Fragment and Activity

  • Activity hands its handler to Fragment
  • broadcast
  • EventBus
  • Define interface

In addition to the methods mentioned above, communication can also be achieved by sharing ViewModel between Activity and Fragment.

Share one last time

[Produced by Tencent Technical Team] Getting started with Android from scratch to mastering it, Android Studio installation tutorial + full set of Android basic tutorials

Android programming introductory tutorial

Java language basics from entry to familiarity

Insert image description here

Kotlin language basics from entry to familiarity

Insert image description here

Android technology stack from entry to familiarity

Insert image description here

Comprehensive learning on Android Jetpack

Insert image description here

For novices, it may be difficult to install Android Studio. You can watch the following video to learn how to install and run it step by step.

Android Studio installation tutorial

Insert image description here

With the Java stage of learning, it is recommended to focus on video learning at this stage and supplement it with book checking and filling in gaps. If you mainly focus on books, you can type the code based on the book's explanations, supplemented by teaching videos to check for omissions and fill in the gaps. If you encounter problems, you can go to Baidu. Generally, many people will encounter entry-level problems and give better answers.

You need to master basic knowledge points, such as how to use the four major components, how to create Service, how to layout, simple custom View, animation, network communication and other common technologies.

A complete set of zero-based tutorials has been prepared for you. If you need it, you can add the QR code below to get it for free.

A complete set of basic Android tutorials

Insert image description here

Insert image description here

Insert image description here

Insert image description here
Insert image description here
Insert image description here
Insert image description here

Guess you like

Origin blog.csdn.net/Android23333/article/details/132563179