Android基础开发之Fragment的简单使用(动态加载)

1、参照Android基础开发之Fragment的简单使用(静态加载)添加两个Fragment的类及布局文件;
2、在Activity的布局文件中添加两个按钮用来进行Fragment的切换;
3、在Activity的布局文件中添加一个FrameLayout布局用于Fragment的显示;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
< ?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="vertical"
    android:weightSum="2"
    tools:context="com.yusian.fragment.MainActivity">
 
    <button android:id="@+id/btn_frag_a"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="A"></button>
 
    <button android:id="@+id/btn_frag_b"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="B"></button>
 
    <framelayout android:id="@+id/fl_fragment"
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
 
    </framelayout>
</linearlayout>

4、Fragment的切换涉及到Fragment的两个类:FragmentManager与FragmentTransaction;
5、切换Fragment三步曲:beginTransaction()—>replace()—>commit();

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.yusian.fragment;
 
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
 
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    Button fragmentA, fragmentB;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fragmentA = (Button)findViewById(R.id.btn_frag_a);
        fragmentB = (Button)findViewById(R.id.btn_frag_b);
        fragmentA.setOnClickListener(this);
        fragmentB.setOnClickListener(this);
    }
 
    @Override
    public void onClick(View v) {
        FragmentManager fragMgr = getFragmentManager();
        FragmentTransaction transaction = fragMgr.beginTransaction();
        if (v == fragmentA){
            System.out.println("点击了A按钮");
            transaction.replace(R.id.fl_fragment, new AFragment());
        }else{
            System.out.println("点击了B按钮");
            transaction.replace(R.id.fl_fragment, new BFragment());
        }
        transaction.commit();
    }
}

6、效果图

Leave a Reply