Fragment碎片的基本使用(手机平板需要更好地兼容)

碎片(Fragment)是一种可以嵌入在活动当中的UI片段,它能让程序更加合理和充分地利用大屏幕的控件,因而在平板上应用得非常广泛。碎片其实与活动十分相似,同样都能包含布局,也同样拥有着自己的生命周期。你甚至可以将碎片理解成一个迷你型的活动,虽然这个迷你型的活动有可能和普通的活动是一样大的。接下来我们来了解下Fragment的具体使用。

新建一个FragmentTest项目,并且创建好一个平板模拟器,Android版本就8.0吧,虽然已经有9.0版本了,但是我发现个别平板模拟器无法自适应重力感应。

创建平板的步骤:

1.点击AVD Manager(AndroidVirtualDevice Manager)

2.点击左下角的Create Virtual Device...

3.选择Tablet,尺寸就选择一个8.86寸的吧

4.下面是选择一个Android设备的版本,这里如果你没有就需要下载一下,我选择的是8.1版本的

5.然后下一步下一步就创建好了

6.启动模拟器

具体请看图解:

这就把Android平板模拟器给创建好了。

我们准备先写一个最简单的碎片示例来练一练手,在一个活动当中添加两个碎片,并且让这两个碎片平分活动空间。

新建一个左侧碎片布局left_fragment.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">

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="btn"
        android:textAllCaps="false" />
    
</LinearLayout>

这个布局很简单,只是放置了一个Button按钮,并且让它水平居中。然后新建右侧碎片布局right_fragment.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:background="#00ff00"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="This is right fragment"
        android:textSize="20sp" />

</LinearLayout>

可以看到,我们将这个布局的背景色设置成了绿色,并放置了一个TextView用于显示一段文本。

接着新建一个LeftFragment类,并让它继承自Fragment。注意,这里可能会有两个不同包下的Fragment供你选择,一个是系统内置的android.app.Fragment,一个是support-v4库中的android.support.v4.app.Fragment。这里我强烈建议你使用support-v4库(注意是support-v4)中的Fragment,因为它可以让碎片在所有Android系统版本中保持功能一致性。比如说在Fragment中嵌套使用Fragment,这个功能是在Android4.2系统中才开始支持的,如果你使用的是系统内置的Fragment,那么很遗憾,4.2系统之前的设备运行你的程序就会崩溃。而使用support-v4库中的Fragment就不会出现这个问题,只要你保证使用的是最新的support-v4库就可以了。另外,我们并不需要在build.gradle文件中添加support-v4库依赖,因为build.gradle文件已经添加了appcompat-v7库的依赖,而这个库会将support-v4库也一起引入进来。

现在编写一下LeftFragment中的代码,如下所示:

package com.example.administrator.fragmenttest;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class LeftFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.left_fragment, container, false);
        return view;
    }
}

这里仅仅是重写了Fragment的onCreateView()方法,然后在这个方法通过LayoutInflater的inflate()方法将刚才定义的left_fragment布局动态加载进来,整个方法简单明了。接着我们用同样的方法再新建一个RightFragment,代码如下所示:

package com.example.administrator.fragmenttest;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class RightFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.right_fragment, container, false);
        return view;
    }
}

接下来修改activity_main.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="horizontal">

    <fragment
        android:id="@+id/left_fragment"
        android:name="com.example.administrator.fragmenttest.LeftFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />

    <fragment
        android:id="@+id/right_fragment"
        android:name="com.example.administrator.fragmenttest.RightFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />
</LinearLayout>

效果图:

正如我们所期待的一样,两个碎片平分了整个活动的布局。不过这个例子实在是太简单了,在真正的项目中很难有什么实际的作用,因此我们马上来看一看关于碎片更加高级的使用技巧。

动态添加碎片:

碎片真正强大之处在于,它可以在程序运行时动态地添加到活动当中。根据具体情况来动态地添加碎片,你就可以将程序界面定制得更加多样化。

新建another_right_fragment.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:background="#ffff00"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="This is another right fragment"
        android:textSize="20sp" />

</LinearLayout>

这个布局文件的代码和right_fragment.xml中的代码基本相同,只是将背景色改成了黄色,并将显示的文字改了改。然后新建AnotherRightFragment.java作为另一个右侧碎片,代码如下所示:

package com.example.administrator.fragmenttest;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class AnotherRightFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.another_right_fragment, container, false);
        return view;
    }
}

代码同样非常简单,在onCreateView()方法中加载了刚刚创建的another_right_fragment布局。这样我们就准备好了另外一个碎片,接下来看一下如何将它动态地添加到活动当中。

修改activity_main.xml代码(删除右边的<fragment/>标签,添加一个<FrameLayout/>):

<?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="horizontal">

    <fragment
        android:id="@+id/left_fragment"
        android:name="com.example.administrator.fragmenttest.LeftFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />

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

</LinearLayout>

可以看到,现在将右侧碎片替换成了一个FrameLayout中,这是Android中最简单的一种布局,所有的控件默认都会摆放在布局的左上角。由于这里仅需要在布局里放入一个碎片,不需要任何定位,因此非常适合使用FrameLayout。

下面我们将在代码中向FrameLayout里添加内容,从而实现动态添加碎片的功能。修改MainActivity中的代码,如下所示:

package com.example.administrator.fragmenttest;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.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 {
    private Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        btn = (Button) findViewById(R.id.btn);
    }

    @Override
    protected void onResume() {
        super.onResume();
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                replaceFragment(new AnotherRightFragment());//替换布局文件
            }
        });
    }

    private void replaceFragment(Fragment fragment) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.right_layout, fragment);
        fragmentTransaction.commit();
    }

}

可以看到,首先我们给左侧碎片中的按钮注册了一个点击事件,然后调用了我们自定义的一个replaceFragment()方法动态添加了RightFragment这个碎片。当点击左侧碎片中的按钮时,又会调用replaceFragment()方法将右侧碎片替换成AnotherRightFragment。结合replaceFragment()方法中的代码可以看出,动态添加碎片主要分为以下几个步骤:

步骤1:创建待添加的碎片实例

步骤2:创建FragmentManager(碎片管理器),通过getSupportFragmentManager()这个方法得到。

步骤3:开启一个FragmentTransaction事务,通过beginTransaction()方法开启

步骤4:向容器内添加或替换碎片,一般使用replace()方法实现,需要传入容器的id和待添加的碎片实例。

步骤5:提交事务,调用commit()方法来完成。

这样就完成了活动中动态添加碎片的功能,重新运行一下程序。

实现效果图:

点击btn按钮:

 

在碎片中模拟返回栈

一行代码:

fragmentTransaction.addToBackStack(null);//接收一个名字用于描述返回栈的状态。

MainActivity.java代码:

package com.example.administrator.fragmenttest;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.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 {
    private Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        btn = (Button) findViewById(R.id.btn);
    }

    @Override
    protected void onResume() {
        super.onResume();
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                replaceFragment(new AnotherRightFragment());//替换布局文件
            }
        });
    }

    private void replaceFragment(Fragment fragment) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.right_layout, fragment);
        fragmentTransaction.addToBackStack(null);//接收一个名字用于描述返回栈的状态。
        fragmentTransaction.commit();
    }

}

这样就可以在点击btn按钮之后,点击手机back按钮就可以将碎片返回,再点击btn按钮,它又可以出来,就像返回栈中压栈、出栈一样。

 

碎片和活动之间进行通信:

虽然碎片都是嵌入在活动中显示的,可是实际上它们的关系并没有那么亲密。你可以看出,碎片和活动都是各自存在于一个独立的类当中的,它们之间并没有那么明显的方式来直接进行通信。如果想要在活动中调用碎片里的方法,或者在碎片中调用活动里的方法,应该如何实现呢?

为了方便碎片和活动之间进行通信,FragmentManager提供了一个类似于findViewById()的方法,专门用于从布局文件中获取碎片的实例,代码如下所示:

Activity中获取Fragment实例:

RightFragment right=(RightFragment) getSupportFragmentManager().findFragmentById(R.id.right_fragment);

调用FragmentManager的findFragmentById()方法,可以在活动中得到相应碎片的实例,然后就能轻松地调用碎片里的方法了。

Fragment中调用Activity实例:

MainActivity activity=(MainActivity) getActivity(); 

 

 

 

 

 

 

猜你喜欢

转载自blog.csdn.net/android_studying/article/details/86135204