Android之碎片Fragment

Fragment是个特别的存在,有点像报纸上的专栏,看起来只占据页面的一小块,但是这一小块有自己的生命周期,可以自行其是,仿佛独立王国,并且这一小块的特性无论在哪个页面,给一个位置就行,添加以后不影响宿主页面的其他区域,去除后也不影响宿主页面的其他区域。每个fragment都有自己的布局文件,依据其使用方式可分为静态注册和动态注册两种,静态注册是在布局文件中直接放置fragment节点,类似于一个普通控件,可被多个布局文件同时引用。静态注册一般用于某个通用的页面部件(如logo条,广告条等),每个活动页面均可直接引用该部件。

1.静态注册

下面是fragment布局文件的代码:

<?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="wrap_content"
    android:orientation="horizontal"
    android:background="#bbffbb">
    <TextView
        android:id="@+id/tv_adv"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:textColor="#000"
        android:textSize="20sp"
        android:gravity="center"
        android:text="广告"/>
    <ImageView
        android:id="@+id/iv_adv"
        android:layout_width="0dp"
        android:layout_height="100dp"
        android:layout_weight="5"
        android:src="@drawable/adv"
        android:scaleType="fitCenter"/>
</LinearLayout>

下面是与上述文件对应的fragment代码,除了继承自fragment外,其他地方很像活动页代码:

package com.example.animator.highleveltools;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.zip.Inflater;

public class BlankFragment extends Fragment implements View.OnClickListener{

    private View mView;
    private Context mContext;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mContext = getActivity();//获取活动页上下文
        //根据布局文件fragment_static.xml生成视图对象
        mView = inflater.inflate(R.layout.fragment_layout,container,false);
        TextView tv_adv = (TextView) mView.findViewById(R.id.tv_adv);
        ImageView iv_adv = (ImageView) mView.findViewById(R.id.iv_adv);
        tv_adv.setOnClickListener(this);
        iv_adv.setOnClickListener(this);
        return mView;//返回该碎片的视图对象
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onClick(View view) {
        if(view.getId()==R.id.tv_adv){
            Toast.makeText(mContext,"您点击了广告文本",Toast.LENGTH_LONG).show();
        }else if(view.getId()==R.id.iv_adv){
            Toast.makeText(mContext,"您点击了广告图片",Toast.LENGTH_LONG).show();
        }
    }
}

若想在页面布局文件中引用fragment,则可直接加入一个fragment节点,注意节点要增加name属性指定fragment类的完整路径

<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:padding="5dp"
    >

    <fragment
        android:id="@+id/fragment_static"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:name="com.example.animator.highleveltools.BlankFragment"
        tools:layout="@layout/fragment_layout" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center|top"
        android:text="这是每个页面的具体内容"
        android:textColor="#000"
        android:textSize="17sp"/>
</LinearLayout>

运行效果如下:

2.动态注册

相比静态注册,动态注册用的更多,动态注册知道在代码中才动态添加fragment,动态生成的碎片就是给翻页视图用的。使用碎片适配器即可实现:

package adapter;

import android.app.FragmentManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.text.style.DynamicDrawableSpan;

import java.util.ArrayList;

import bean.DynamicFragment;

/**
 * Created by animator on 2020/1/29.
 */
public class MobilePagerAdapter extends FragmentStatePagerAdapter {
    private ArrayList<GoodsInfo> mGoodsList = new ArrayList<>();//声明一个商品队列

    //碎片页适配器的构造函数,传入碎片管理器与商品信息队列
    private MobilePagerAdapter(android.support.v4.app.FragmentManager fm , ArrayList<GoodsInfo> goodsList){
        super(fm);
        mGoodsList = goodsList;
    }

    //获取指定位置的fragment
    @Override
    public Fragment getItem(int position) {
        return DynamicFragment.newInstance(position,mGoodsList.get(position).pic,mGoodsList.get(position).desc);
    }

    //获取碎片fragment的个数
    @Override
    public int getCount() {
        return mGoodsList.size();
    }

    //获得指定碎片页的标题文本
    public CharSequence getPageTitle(int position){
        return mGoodsList.get(position).name;
    }
}

下面是动态注册的碎片代码:

package bean;

import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.animator.highleveltools.R;

/**
 * Created by animator on 2020/1/29.
 */
public class DynamicFragment extends Fragment {
    protected View mView;//声明一个视图对象
    protected Context mContext;//声明一个上下文对象
    private int mPosition;//位置序号
    private int mImageId;//图片的资源编号
    private String mDesc;//商品的文字描述

    //获取该碎片的一个实例
    public static DynamicFragment newInstance(int position,int image_id,String desc){
        DynamicFragment fragment = new DynamicFragment();//创建该碎片的一个实例
        Bundle bundle = new Bundle();//创建一个新包裹
        bundle.putInt("position",position);
        bundle.putInt("image_id",image_id);
        bundle.putString("desc",desc);
        fragment.setArguments(bundle);//把包裹塞给碎片
        return fragment;
    }

    //创建碎片视图
    public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState){
        mContext = getActivity();
        if(getArguments()!=null){//如果碎片携带有包裹
            mPosition = getArguments().getInt("position");
            mImageId = getArguments().getInt("image_id");
            mDesc = getArguments().getString("desc");
        }
        //根据布局文件fragment_dynamic.xml生成视图对象
        mView = inflater.inflate(R.layout.fragment_dynamic,container,false);
        ImageView iv_pic = mView.findViewById(R.id.iv_pic);
        TextView tv_desc = (TextView) mView.findViewById(R.id.tv_desc);
        iv_pic.setImageResource(mImageId);
        tv_desc.setText(mDesc);
        return mView;//返回该碎片的视图对象
    }
}

下面是activity代码:

     ArrayList<GoodsInfo> goodsList = GoodsInfo.getDefaultList();
        //构建一个手机商品的碎片翻页适配器
        MobilePagerAdapter adapter = new MobilePagerAdapter(getSupportFragmentManager(),goodsList);
        //从布局视图中获取名叫vp_content的翻页视图
        ViewPager vp_content = findViewById(R.id.vp_content);
        //给vp_content设置手机商品的碎片适配器
        vp_content.setAdapter(adapter);
        //设置vp_content默认显示第一个页面
        vp_content.setCurrentItem(0);

原文地址:https://www.cnblogs.com/zdm-code/p/12240988.html

时间: 2024-08-27 02:42:12

Android之碎片Fragment的相关文章

Android开发:碎片Fragment完全解析fragment_main.xml/activity_main.xml

Android开发:碎片Fragment完全解析 为了让界面可以在平板上更好地展示,Android在3.0版本引入了Fragment(碎片)功能,它非常类似于Activity,可以像 Activity一样包含布局.Fragment通常是嵌套在Activity中使用的,现在想象这种场景:有两个 Fragment,Fragment 1包含了一个ListView,每行显示一本书的标题.Fragment 2包含了TextView和 ImageView,来显示书的详细内容和图片. AD:51CTO学院:I

Android开发 碎片Fragment的API全解与标准使用

前言 我还在学习Android开发的时候发过一篇简单的入门Fragment demo代码:https://www.cnblogs.com/guanxinjing/p/9708626.html 但是,Fragment远远不是一个简单的Demo就能了解清楚的,所以此篇博客将讲解FragmentManage的Api的功能 如何获取FragmentManage activity里获取FragmentManage方式如下: @Override protected void onCreate(Bundle

Android碎片Fragment总结

一.Fragment的相关概念 (一)Fragment的基础知识 Fragment是Android3.0新增的概念,中文意思是碎片,它与Activity十分相似,用来在一个 Activity中描述一些行为或一部分用户界面.使用多个Fragment可以在一个单独的Activity中建 立多个UI面板,也可以在多个Activity中使用Fragment. Fragment拥有自己的生命 周期和接收.处理用户的事件,这样就不必在Activity写一堆控件的事件处理的代码了.更为 重要的是,你可以动态的

android学习八(android碎片fragment的使用)

碎片(Fragment)是一种可以嵌入在活动当中的UI片段,它能让程序更加合理和充分地利用屏幕的空间.首先建立一个平板的模拟器1034*600,环境使用android4.2.2.在建立一个android的项目,项目名为FragmentTest. 碎片的简单使用 新建一个左侧碎片布局left_fragment.xml代码如下 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:andr

Android 关于ViewPager结合碎片Fragment的简单使用

一.      首先在xml添加ViewPager控件 我们希望每个viewpager显示一张图片 新建一个pager_item.xml的文件 代码如下 二.分析   一个ViewPager需要设置一个适配器,这个适配器可以继承FragmentStatePagerAdapter, 适配器同样需要设置数据,这个为适配器添加的是碎片.碎片可以继承Fragment,设置视图,监听等,具体图如下: 三.    上图可知,我们需要新建一个碎片先. 注意,这个继承的Fragment需要是在包android.

Android 开发 之 Fragment 详解

作者 : 韩曙亮 转载请著名出处 : http://blog.csdn.net/shulianghan/article/details/38064191 1. Fragement 概述 Fragement 与 Activity 生命周期关系 : Fragement 嵌入到 Activity 组件中才可以使用, 其生命周期与 Activity 生命周期相关. -- stop 与 destroy 状态 : Activity 暂停 或者 销毁的时候, 其内部嵌入的所有的 Fragement 也会执行

Android系列之Fragment(一)----Fragment加载到Activity当中

Android系列之Fragment(一)----Fragment加载到Activity当中 ?[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/3978989.html 联系方式:[email protected] [正文] Android上的界面展示都是通过Activity实现的,Activity实在是太常用了.但是Activity也有它的局限性

android笔记4——Fragment的使用

说明第一下:按照前面的方式我们创建了项目,如果使用的是最新的ADT,Minimum Android SDK选的是android2.*或1.*,此时会默认创建一个兼容的项目,--appcompat_v7,这个项目还是不能删除的,删除会报错.. 说明第二下:项目创建好了之后,发现layout文件夹(布局)中会有默认两个文件:adtivity和fragment文件: 1.Fragment概述: Fragment意思为碎片,片段,说白了就是模块,说道模块,就不用我多说了.. 特征: Fragment总是

Android -- TabHost、Fragment、状态保存、通信

工程结构                                                                                       TabAFm到TabEFm都是Fragment,并且每个Fragment对应一个布局文件. TabAFm.java                                                                             package com.yydcdut.tabho