Fragment学习

本文介绍了Android中的Fragment使用,包括在MainActivity中如何创建和管理三个Fragment,每个Fragment对应不同的布局,展示了Fragment在界面构建中的作用。
摘要由CSDN通过智能技术生成

Fragment学习


    Fragment可以看作是一种轻量级的Activity,它像Activity一样具有生命周期,也可以有自己的布局和输入事件,但是它比Activity更加灵活。Fragment的目的是适配不同终端屏幕分辨率,确保软件在不同终端上都有良好的用户体验。
    本文实现了Fragment的基本使用和动态切换。
    1.定义Fragment类(extends Fragment)和对应的布局文件,将Fragment对应的view绑定上(如果有的话)。这里app.Fragment和v4.app.Fragment好像在效果上没啥区别,由于我更在意基本的使用,也没细看文档里的差别。
    2.在主函数中定义点击事件用来动态切换fragment。
    代码如下:
    1.三个Fragment,AboveFragment生成上方Fragment,BelowFragment生成下方Fragment,SecondAboveFragment是点击事件发生时切换到新的Fragment。
package com.bupt.markfavor.demo0916fragment;

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

/**
 * Created by markfavor on 2017/9/16.
 */

public class AboveFragment extends Fragment{
   
    public static AboveFragment instance = new AboveFragment();
    public static AboveFragment getInstance(){
        return instance;
    }

    private TextView myTextView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.layout_above,container,false);
        myTextView = (TextView) view.findViewById(R.id.tv1);
        return view;
    }
}
package com.bupt.markfavor.demo0916fragment;

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

/**
 * Created by markfavor on 2017/9/16.
 */

public class BelowFragment extends Fragment {
   

    private TextView myTextView;

    public  static  BelowFragment instance=new BelowFragment();
    public  static  BelowFragment getInstance(){
        return instance;
    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGro
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值