Android Fragment 的静态和动态使用

 

文章目录

 


前言

手机平板已经极大融入了我们的生活,随着各种APP的推出,人们对程序的要求重心也从功能慢慢偏向页面,一个优美的页面也会在众多的APP中脱颖而出

举个例子,现在的新闻APP众多,对于手机,点击标题跳转至内容页面是很常见的,但是对于平板,如果采用这种模式,将会有大量的留白

                     

可以看的出来这样很不美观,但是我们可以将新闻标题列表界面和新闻详细内容界面分别放在一起,此处就需要用到碎片技术,就也可实现我们熟悉的平板新闻APP界面


 

一、Fragment是什么?

             碎片是一种可以嵌入到活动中的UI片段,一个和页面可以被多个碎片填充,这样一来就可以让页面被充分合理的填充比较大的页面,因此碎片在尺寸比较大的平板上有广泛的使用.

二、使用分类

1.静态添加碎片

  (1). 首先创建两个碎片布局,此处我为了演示,创建了简单的布局

      布局文件: right.xml

       此处布局文件很简单,只放了一个TextView控件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
<TextView
    android:id="@+id/right"
    android:text="我是right"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>
</LinearLayout>

  布局文件: left.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
<Button
    android:id="@+id/left"
    android:text="我是left"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>
</LinearLayout>

  (2). 创建两个类,分别为RightFragment 和 LeftFragment ,他们都继承自 Fragment ,因为 Fragment 中嵌套 Fragment 在 Android 4.2 中才支持,因为为了让碎片在所有的 Android 版本中保持一致性,我们导包的时候选择 support-v4.

  RightFragment.java

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

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,container,false);
        return view;
    }
}

LeftFragment.java

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class LeftFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.left,container,false);
    }
}

 : 上述代码也仅仅是重写 Fragment 的 onCreateView() 方法,然后通过 LayoutInflater 的 inflate() 方法将刚才定义的碎片布局文件 right.xml 和 left.xml 加载进来

   (3). 在 layout_main.xml 文件中加入 fragment 布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <fragment
        android:id="@+id/leftFragment"
        android:name="com.example.fragmenttest.LeftFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"/>
    <fragment
        android:id="@+id/rightFragment"
        android:name="com.example.fragmenttest.RightFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"/>
</LinearLayout>

我们在 fragment标签中添加碎片,其中需要使用  android.name 属性来指定压迫添加的碎片类名,注意要加上包名

接下来运行程序,效果图如下

2.动态添加碎片

    通过上面的例子,我们已经掌握了在布局文件中添加碎片的方法,不过,为了实现平板新闻页面的效果,我们需要见识一下碎片的强大之处,即在程序运行时动态添加到活动中,根据情况动态的添加碎片,就可以简单实现我们想要的效果

   (1). 我们接下来修改 layout_main.xml 布局,布局中将逻辑布局上的右碎片替换成 FrameLayout 控件

   注意:这里的FrameLayout 没有 android.name 属性

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <fragment
        android:id="@+id/leftFragment"
        android:name="com.example.fragmenttest.LeftFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"/>
    <FrameLayout
        android:id="@+id/myFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"/>
</LinearLayout>

(2). 接下来修改主活动 (MainActivity.java) 中的代码

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

/**
 * 动态添加碎片的步骤
 *  1. 创建待替换的碎片实例
 *  2. 获取 FragmentManager的实例,在活动中可通过 getSupportFragmentManager()方法获取
 *  3. 开始一个事务,调用 getSupportFragmentManager().beginTransaction() 方法获取实例
 *  4. 使用事务对象的 replace() 方法,
 *     即 getSupportFragmentManager().beginTransaction().replace(容器 id , 碎片实例)
 *  5. 提交事务,使用 getSupportFragmentManager().beginTransaction().commit() 方法提交
 *  6. 碎片替换完成
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    FrameLayout myFragment;
    Button button;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_main);
       /**初始化控件,绑定监听*/
        init();
    }

    /**
     * 监听事件
     * @param view
     */
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.left:
                /**
                 * 如果 myFragment 可见,就设为不可见,反之设为可见
                 */
                if (myFragment.getVisibility() == View.VISIBLE){
                    myFragment.setVisibility(View.INVISIBLE);
                }
                else {
                    myFragment.setVisibility(View.VISIBLE);
                    /**
                     * 实例化待添加的碎片类,进行碎片替换
                     */
                    replaceFragment(new RightFragment());
                }
                break;
            default:
                break;
        }
    }
    private void init(){
        myFragment = findViewById(R.id.myFragment);
        myFragment.setVisibility(View.INVISIBLE);
        button = findViewById(R.id.left);
        button.setOnClickListener(this);
    }
    @SuppressLint("ResourceType")
    public void replaceFragment(Fragment fragment){
        /**获取 FragmentManager 实例对象*/
        FragmentManager fragmentManager = getSupportFragmentManager();
        /**获取 FragmentTransaction 实例对象*/
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        /**传入容器 id 和碎片类实例进行替换*/
        fragmentTransaction.replace(R.id.myFragment,fragment);
        /**提交事务*/
        fragmentTransaction.commit();
    }
}

上述代码我主要实现点击按钮,将右边的碎片进行显示时替换,因为比较懒,所以没有去创建一个新的页面进行替换来实现新闻的效果,为了体现出效果就写个隐藏,哈哈哈哈哈,不过看到这儿,大家应该知道怎么做了.

就是我们点击标题,动态的将新闻的内容填入到碎片页的TextView中,并将碎片页的实例传入到替换方法里

程序在平板和手机进行区别显示时,可以借助限定符,这个以后有时间我再补充,感兴趣的道友可以先自行了解一下

附上效果图


总结

碎片是可以让一个程序兼容很多设备的技术,我们考虑的东西多一点点,后面维护就会轻松一些

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值