Android Fragment

Android Fragment

Fragment是什么

是碎片,可以表示Activity中的行为或用户界面部分

为什么要使用Fragment

1.解决局部刷新的问题
2.解决屏幕适配的问题

需要掌握的一些知识点
Fragment静态加载

在xml文件里建fragment标签,用name引用
静态加载:是讲在主布局文件中放入fragment布局,然后使用

下面是一个简单两个fragment碎片的静态加载(fragment一定要写id,name

布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.myapplication.MainActivity">

<fragment
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:name="com.example.myapplication.HelloFragment"
android:id="@+id/hello_fragment"/>
<fragment
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:id="@+id/list_fragment"
android:name="com.example.myapplication.ListFragment"/>

</LinearLayout>

新建的两个fragment里面都不要改,只要设置一下背景颜色来辨别就行
效果图:这里写图片描述

Fragment动态加载

动态加载:不需要在主布局文件中去声明fragment的,而是直接在java代码中去添加

ViewPager页码的滑动(页卡适配器控件)
<android.support.v4.view.ViewPager
android:id="@+id/vp"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
ViewPager+Fragment实现页卡滑动

下面代码是一个简单的页卡滑动效果
1.第一个fragment的布局文件:

<FrameLayout 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:background="@color/colorPrimary"
    tools:context="com.example.myapplication.fragment_vp.ContFragment">
    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="消息"
        android:gravity="center"/>
</FrameLayout>

2.第二个fragment的布局文件:

<FrameLayout 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:background="@color/colorPrimary"
    tools:context="com.example.myapplication.fragment_activity.DongFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="动态"
        android:textSize="30sp"
        android:gravity="center"/>

</FrameLayout>

3.第三个fragment的布局文件:

<FrameLayout 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:background="@color/colorAccent"
    tools:context="com.example.myapplication.fragment_vp.FriendFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="朋友圈"
        android:gravity="center"/>

</FrameLayout>

4.新建一个适配器,继承FragmentPagerAdapter

package com.example.myapplication.adapter;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import java.util.List;

/**
 * Created by lyj on 2018/6/5.
 */

public class ViewpagerAdapter extends FragmentPagerAdapter{
    List<Fragment> fragmentList;
    public ViewpagerAdapter(FragmentManager fm,List<Fragment> fragmentList) {
        super(fm);
        this.fragmentList=fragmentList;
    }

    @Override
    public Fragment getItem(int position) {
        return fragmentList.get(position);
    }

    @Override
    public int getCount() {
        return fragmentList.size();
    }
}

6.主类的布局文件(做的有点丑,不是很美观)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.myapplication.ViewpagerActivity">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">
        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:textSize="25sp"
            android:gravity="center"
            android:text="聊天"
            android:id="@+id/cont"/>
        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:textSize="25sp"
            android:gravity="center"
            android:text="好友"
            android:id="@+id/friend"/>
        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:textSize="25sp"
            android:gravity="center"
            android:text="朋友圈"
            android:id="@+id/my"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="3dp"
        >
        <View
            android:layout_width="0dp"
            android:layout_height="3dp"
            android:layout_weight="1"
            android:background="#0000ff"
            android:id="@+id/cont_view"/>
        <View
            android:layout_width="0dp"
            android:layout_height="3dp"
            android:layout_weight="1"
            android:id="@+id/friend_view"/>
        <View
            android:layout_width="0dp"
            android:layout_height="3dp"
            android:layout_weight="1"
            android:id="@+id/my_view"/>
    </LinearLayout>
    <android.support.v4.view.ViewPager
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="8"
        android:id="@+id/vp">
    </android.support.v4.view.ViewPager>

</LinearLayout>

7.activity类(setCurrentItem();跳转到ViewPager的指定页面)

package com.example.myapplication;

import android.graphics.Color;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.example.myapplication.adapter.ViewpagerAdapter;
import com.example.myapplication.fragment_vp.ContFragment;
import com.example.myapplication.fragment_vp.FriendFragment;
import com.example.myapplication.fragment_vp.MyFragment;

import java.util.ArrayList;
import java.util.List;

public class ViewpagerActivity extends AppCompatActivity implements View.OnClickListener {
    private TextView cont, friend, my;
    private View cont_view, friend_view, my_view;
    private ViewPager vp;
    private ContFragment contFragment;
    private FriendFragment friendFragment;
    private MyFragment myFragment;
    List<Fragment> fragmentList = new ArrayList<>();

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

        cont = findViewById(R.id.cont);
        friend = findViewById(R.id.friend);
        my = findViewById(R.id.my);
        //绑定id到点击事件
        cont.setOnClickListener(this);
        friend.setOnClickListener(this);
        my.setOnClickListener(this);

        vp = findViewById(R.id.vp);

        cont_view = findViewById(R.id.cont_view);
        friend_view = findViewById(R.id.friend_view);
        my_view = findViewById(R.id.my_view);

        contFragment = new ContFragment();
        friendFragment = new FriendFragment();
        myFragment = new MyFragment();

        fragmentList.add(contFragment);
        fragmentList.add(friendFragment);
        fragmentList.add(myFragment);

        ViewpagerAdapter adapter = new ViewpagerAdapter(getSupportFragmentManager(), fragmentList);
        vp.setAdapter(adapter);
        vp.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                cont_view.setBackgroundColor(Color.GRAY);
                friend_view.setBackgroundColor(Color.GRAY);
                my_view.setBackgroundColor(Color.GRAY);
                switch (position) {
                    case 0:
                        cont_view.setBackgroundColor(Color.BLUE);
                        break;
                    case 1:
                        friend_view.setBackgroundColor(Color.BLUE);
                        break;
                    case 2:
                        my_view.setBackgroundColor(Color.BLUE);
                        break;
                    default:
                        break;
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.cont:
                //点中哪个页卡就到哪个页面
                vp.setCurrentItem(0);
                break;
            case R.id.friend:
                vp.setCurrentItem(1);
                break;
            case R.id.my:
                vp.setCurrentItem(2);
                break;
            default:
                break;
        }
    }
}
fragment的生命周期

当Fragment与Activity发生关联时调用

  • onAttach();依附
  • onCreate();

创建该Fragment的视图

  • onCreateView();
  • onActivityCreated();
  • onStart();
  • onResume();
  • onPause();
  • onStop();
    与onCreateView想对应,当该Fragment的视图被移除时调用
  • onDestroyView();
  • onDestroy();
    与onAttach相对应,当Fragment与Activity关联被取消时调用
  • onDetach();解绑

下面是一个简单的测试和上面的划页的代码是一起联用的

package com.example.myapplication.fragment_vp;


import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.myapplication.R;

/**
 * A simple {@link Fragment} subclass.
 */
public class FriendFragment extends Fragment {

    private String TAG="FriendFragment";

    public FriendFragment() {
        // Required empty public constructor
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Log.d(TAG, "onAttach:********* ");
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate: *********");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        Log.d(TAG, "onCreateView: *********");
        return inflater.inflate(R.layout.fragment_friend, container, false);
    }
    @Override
    public void onStart() {
        super.onStart();
        Log.d(TAG, "onStart: *********");
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "onResume: *********");
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d(TAG, "onPause: *********");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.d(TAG, "onDestroyView: *********");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy:*********");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.d(TAG, "onDetach: *********");
    }

}
fragment之间的传值
  • fragment往activity传值

在activity类中需要建一个方法,把fragment传过来的东西放在某个控件里(我放的是TextView控件)

布局文件先设定一个控件

<TextView
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:id="@+id/title_tv" />

定义

private TextView tv_title;

获取id

 tv_title=findViewById(R.id.title_tv);

这是在activity定义的一个方法

public void modfity(String title){
        tv_title.setText(title);
    }

在fragment类里面需要得到视图

 View v=inflater.inflate(R.layout.fragment_cont, container, false);
 return v;

通过视图获取到fragment布局文件的控件的id

View v=inflater.inflate(R.layout.fragment_cont, container, false);
        title_button=v.findViewById(R.id.title_button1);
        title_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ViewpagerActivity viewpagerActivity= (ViewpagerActivity) getActivity();
                viewpagerActivity.modfity("聊天");
            }
        });
         return v;
  • activity往fragment传值
    在activity类用Bundle存储值,然后把你传的值通过setArguments()方法传到你想传的fragment里面
        Bundle bundle=new Bundle();
        bundle.putString("name","小明");
        contFragment.setArguments(bundle);

在fragment接收,我是把传过来的值显示在按钮控件上

        Bundle bundle=getArguments();
        String name=bundle.getString("name");
        title_button.setText(name);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值