本文主要记录了关于fragment的四种跳转方式:
1、从同一个Activiy的一个Fragment跳转到另外一个Fragment
2、从一个Activity的Fragment跳转到另外一个Activity
3、从一个Activity跳转到另外一个Activity的Fragment上
4、从一个Activity的Fragment跳转到另外一个Activity的Fragment上
写这篇文章只是一个简单的记录,当初我学这里的时候看别人的文章总是觉得云里雾里的,后来自己也觉得差不多可以了,于是写下这篇博客,也是记录自己的学习过程。
首先新建一个项目,然后新建两个活动MainActivity、OtherActivity。
在MainActivity的布局文件中写一个子布局:
1 <?xml version="1.0" encoding="utf-8"?>
2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 android:orientation="vertical"
4 android:layout_width="match_parent"
5 android:layout_height="match_parent">
6
7
8 <FrameLayout
9 android:id="@+id/fragment_container"
10 android:layout_width="match_parent"
11 android:layout_height="0dp"
12 android:layout_weight="1"/>
13
14
15 </LinearLayout>
新建一个my_fragment.xml布局与MyFragment类
1 <?xml version="1.0" encoding="utf-8"?>
2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 android:orientation="vertical"
4 android:layout_width="match_parent"
5 android:layout_height="match_parent">
6
7 <TextView
8 android:layout_width="match_parent"
9 android:layout_height="wrap_content"
10 android:text="MyFragment"
11 android:textSize="40sp"
12 android:gravity="center_horizontal"/>
13
14 <Button
15 android:id="@+id/my_button"
16 android:layout_width="wrap_content"
17 android:layout_height="wrap_content"
18 android:textAllCaps="false"
19 android:text="To YourFragment"/>
20
21 <Button
22 android:id="@+id/my_other"
23 android:layout_width="wrap_content"
24 android:layout_height="wrap_content"
25 android:textAllCaps="false"
26 android:text="To OtherActivity"/>
27
28 </LinearLayout>
MyFragment类就暂时省略了,后面会贴出所有代码。
在MainActivity中先添加进一个Fragment进行最开始的展示(压栈式添加)
1 public class MainActivity extends AppCompatActivity {
2
3 @Override
4 protected void onCreate(Bundle savedInstanceState) {
5 super.onCreate(savedInstanceState);
6 setContentView(R.layout.activity_main);
7 getSupportFragmentManager()
8 .beginTransaction()
9 .replace(R.id.fragment_container,new MyFragment())
10 .addToBackStack(null)
11 .commit();
12
13 }
14 }
从同一个Activiy的一个Fragment跳转到另外一个Fragment
这个跳转与上面初始显示Fragment类似。
新建your_fragment.xml布局与YourFragment类。
1 public class YourFragment extends Fragment {
2 public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
3 View contentView;
4 contentView = inflater.inflate(R.layout.your_fragment, container, false);
5 return contentView;
6 }
7
8 @Override
9 public void onActivityCreated(@Nullable Bundle savedInstanceState) {
10 super.onActivityCreated(savedInstanceState);
11 Button myReturn = (Button) getActivity().findViewById(R.id.my_return);
12 myReturn.setOnClickListener(new View.OnClickListener() {
13 //返回到上一个Fragment(同一个Activity中)
14 @Override
15 public void onClick(View v) {
16