Learn with you for lifeXi, this is Programmer Android
Recommended classic articles. By reading this article, you will gain the following knowledge points:
1. Introduction to Fragment
2. Design principles of Fragment
3. Fragment life cycle
4. How to use Fragment in Activity
5. Method to dynamically add Fragment to Activity
6. Get Fragment in Activity
7. How to get Fragment to host Activity
8. Two Methods for communicating with a Fragment
9. Methods for communicating between Fragment and Activity
10. References
1. Introduction to Fragment
Before learning Fragment, we need to understand the inheritance relationship of Fragment. The inheritance relationship of Fragment is as follows:
java.lang.Object
↳ android.app.Fragment
Fragment
Fragments, Activity
often used in responsible for user interface parts, can be Fragment
combined into one Activity
to create multiple windows UI
, or Activity
reused in a fragment Fragment
. You can Fragment
think of it as Activity
a modular component that Fragment
has its own life cycle, can receive its own input events, and can be Activity
added or removed at runtime Fragment
.
Fragment
Must be nested in Activity
, and its life cycle is Activity
affected by the life cycle.
2. Design principles of Fragment
Fragment
Mainly to provide support for more dynamic and flexible UI
designs on large screens (tablets, etc.). Since tablet screens are much larger than phone screens, there's UI
more space available for combining and swapping components. When Fragment
implementing this type of design, you don't need to manage complex changes to the view hierarchy. By Activity
breaking the layout into parts Fragment
, you can modify the appearance at runtime Activity
and Activity
persist those changes in a managed back stack.
You should Fragment
design each one as a reusable modular Activity
component. That is, since each Fragment
defines its own layout and behavior through its own lifecycle callbacks, you can add one to Fragment
multiple Activity
, so you should adopt a reusable design and avoid directly Fragment
manipulating one from another a Fragment
. This is especially important because modular fragments allow you to Fragment
adapt to different screen sizes by changing the way they are combined. When designing an app that works on both tablets and phones, you can reuse yours in different layout configurations Fragment
to optimize the user experience based on available screen space. For example, on a mobile phone, if Activity
multiple clips cannot be stored in the same one, you may have to use separate clips to achieve a single pane UI
.
Combine two Fragments into one Activity to adapt to tablets, and use one Fragment to adapt to mobile phones
3. Fragment life cycle
1. Fragment life cycle diagram
Fragment life cycle diagram
2. Fragment
Life cycle callback method
public void onAttach(Context context) {
// TODO Auto-generated method stub
Log.i(TAG, "----onAttach----");
super.onAttach(context);
}
@Override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "----onCreate----");
// 在Fragment 中调用Activity 中的方法
((FragmentAutoCreate) getActivity()).test();
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.i(TAG, "----onCreateView----");
// 将layout布局转换成View
View view = inflater.inflate(R.layout.fragment_left_layout, null);
Toast.makeText(getActivity(),
"通过对外提供方法setMsg(String msg),供Activity 调用", 0).show();
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
Log.i(TAG, "----onActivityCreated----");
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
}
@Override
public void onStart() {
Log.i(TAG, "----onStart----");
// TODO Auto-generated method stub
super.onStart();
}
@Override
public void onResume() {
Log.i(TAG, "----onResume----");
// TODO Auto-generated method stub
super.onResume();
}
@Override
public void onPause() {
Log.i(TAG, "----onPause----");
// TODO Auto-generated method stub
super.onPause();
}
@Override
public void onStop() {
Log.i(TAG, "----onStop----");
// TODO Auto-generated method stub
super.onStop();
}
@Override
public void onDestroyView() {
Log.i(TAG, "----onDestroyView----");
// TODO Auto-generated method stub
super.onDestroyView();
}
@Override
public void onDestroy() {
Log.i(TAG, "----onDestroy----");
// TODO Auto-generated method stub
super.onDestroy();
}
@Override
public void onDetach() {
Log.i(TAG, "----onDetach----");
// TODO Auto-generated method stub
super.onDetach();
}
3.Fragment in the life cycle of the host Activity
Fragment
It cannot Activity
exist without separation, and its life cycle is Activity
affected by the life cycle.
Activity and Fragment life cycle interaction diagram
Log print information is as above
4. How to use Fragment in Activity
1. Staticly add Fragment to Activity
<fragment
android:id="@+id/left_fragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
class="com.programandroid.Fragment.FragmentLeft" />
2. Create a custom Fragment class
The implementation method is as follows
public class FragmentRight extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// 将layout布局转换成View
View view = inflater.inflate(R.layout.fragment_right_layout, null);
// 取出值
Bundle values = getArguments();
if (values != null) {
String str = values.getString("key", "");
Toast.makeText(getActivity(), "接收Activity传递的至为:" + str, 0).show();
} else {
Toast.makeText(getActivity(), "接收Activity传递的至为空", 0).show();
}
return view;
}
}
5. Dynamically add Fragment to Activity
1. Create a custom Fragment class
public class FragmentRight extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// 将layout布局转换成View
View view = inflater.inflate(R.layout.fragment_right_layout, null);
// 取出值
Bundle values = getArguments();
if (values != null) {
String str = values.getString("key", "");
Toast.makeText(getActivity(), "接收Activity传递的至为:" + str, 0).show();
} else {
Toast.makeText(getActivity(), "接收Activity传递的至为空", 0).show();
}
return view;
}
}
2. Create a Fragment to fill the layout vector
<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" >
<FrameLayout
android:id="@+id/fl_left"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#f00" />
<FrameLayout
android:id="@+id/fl_right"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:background="#0f0" />
</LinearLayout>
3. Use FragmentManager to dynamically populate
1. Create the container that the container Fragment
receives Activity
.
2. Use FragmentManager
and Fragment
interact with
3. Open the transaction and the created container will Fragment
be filled. 4. Submit the transaction.Activity
public class FragmentAutoCreate extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment_autocreate);
// 获取fragmentManager --->开启事务--->容器中填充内容--->提交事务
// FragmentManager : Activity 内部用来与Fragment进行交互的接口
FragmentManager fragmentManager = getFragmentManager();
// 开启一个事务
FragmentTransaction transaction = fragmentManager.beginTransaction();
// 将左右两侧的Fragment 添加的R.id.fl_left 所代表的容器视图中
FragmentLeft leftFragment = new FragmentLeft();
transaction.add(R.id.fl_left, leftFragment, "left_tag");
// 1. 调用 Fragment 对外提供的方法
leftFragment.setMsg("tttt");
FragmentRight rightFragment = new FragmentRight();
// 2. Activity --setArguments-> 创值给Fragment
Bundle args = new Bundle();
args.putString("key", "Activity --setArguments-> 创值给Fragment ");
// 传递数据
rightFragment.setArguments(args);
transaction.add(R.id.fl_right, rightFragment);
// transaction.replace(R.id.fl_right, rightFragment);
// transaction.hide(rightFragment);
transaction.show(rightFragment);
// 提交事务
transaction.commit();
}
public void test() {
}
}
6. Obtain Fragment from Activity
Fragment idFragment=getFragmentManager().findFragmentById(R.id.fl_left);
FragmentRight tagFragment = (FragmentRight) getFragmentManager().findFragmentByTag("left_tag");
7. Fragment’s method of obtaining the host Activity
1. getActivity()
Method to obtain宿主Activity
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.i(TAG, "----onCreateView----");
// 将layout布局转换成View
View view = inflater.inflate(R.layout.fragment_left_layout, null);
Toast.makeText(getActivity(),
"通过对外提供方法setMsg(String msg),供Activity 调用", 0).show();
return view;
}
8. Communication method between two Fragments
1. Obtain different values through the host Activity
to methodFragmentManger
Fragment
Fragment idFragment=getFragmentManager().findFragmentById(R.id.fl_left);
FragmentRight tagFragment = (FragmentRight) getFragmentManager().findFragmentByTag("left_tag");
9. Communication method between Fragment and Activity
1.Activity calls the setArguments method
public class FragmentAutoCreate extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment_autocreate);
// 获取fragmentManager --->开启事务--->容器中填充内容--->提交事务
// FragmentManager : Activity 内部用来与Fragment进行交互的接口
FragmentManager fragmentManager = getFragmentManager();
// 开启一个事务
FragmentTransaction transaction = fragmentManager.beginTransaction();
// 将左右两侧的Fragment 添加的R.id.fl_left 所代表的容器视图中
FragmentLeft leftFragment = new FragmentLeft();
transaction.add(R.id.fl_left, leftFragment, "left_tag");
// 1. 调用 Fragment 对外提供的方法
leftFragment.setMsg("tttt");
FragmentRight rightFragment = new FragmentRight();
// 2. Activity --setArguments-> 创值给Fragment
Bundle args = new Bundle();
args.putString("key", "Activity --setArguments-> 创值给Fragment ");
// 传递数据
rightFragment.setArguments(args);
transaction.add(R.id.fl_right, rightFragment);
// transaction.replace(R.id.fl_right, rightFragment);
// transaction.hide(rightFragment);
transaction.show(rightFragment);
// 提交事务
transaction.commit();
}
public void test() {
}
}
2. Provide interface methods to the outside world through Fragment
By Fragment
providing external interface methods for Activity
calling
public class FragmentLeft extends Fragment {
private static final String TAG = " F wj";
private String mMessage;
public void setMsg(String msg) {
this.mMessage = msg;
}
@Override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "----onCreate----");
// 在Fragment 中调用Activity 中的方法
((FragmentAutoCreate) getActivity()).test();
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.i(TAG, "----onCreateView----");
// 将layout布局转换成View
View view = inflater.inflate(R.layout.fragment_left_layout, null);
Toast.makeText(getActivity(),
"通过对外提供方法setMsg(String msg),供Activity 调用", 0).show();
return view;
}
references:
[Tencent Documentation] Android basic knowledge base
https://docs.qq.com/doc/DSWdKRWh1VnVHYWFP
Friendly recommendation:
Collection of useful information on Android development
At this point, this article has ended. The editor thinks the article is reprinted from the Internet and is excellent. You are welcome to click to read the original article and support the original author. If there is any infringement, please contact the editor to delete it. Your suggestions and corrections are welcome. We look forward to your attention and thank you for reading, thank you!
Click to read the original article and like the boss!