安卓开发学习9:Fragment

解析

类似于Activity,可以用来在Activity中描述一些行为或者描述一部分页面,也可以使用多个Fragment在一个Activity中创建多个UI面板,一个Fragment必须嵌入到一个Activity中,只有Activity处于运行状态才可以对Fragment操作
在这里插入图片描述

Fragment声明周期

在这里插入图片描述

创建Fragment

Android Studio进行快捷创建Fragment

可以通过Android Studio进行快捷创建Fragment
在这里插入图片描述

Fragment解析

Fragment可以作为Activity的一部分,那么就可以创建自己的布局文件
在这里插入图片描述
并且创建Fragment对应的类

public class BlankFragment extends Fragment

并在onCreateView方法中关联刚才创建的xml文件

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // R.layout.fragment_blank为关联的xml文件
    return inflater.inflate(R.layout.fragment_blank, container, false);
}

在Acitivity中添加Fragment

1、方式一:直接在布局文件中添加Fragment

直接在xml文件中通过fagment进行添加。其中name属性制定fagment文件的路径

<fragment
     android:id="@+id/blank2"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_weight="1"
     android:name="com.example.study2.BlankFragment2"
     ></fragment>

注意需要添加id并且制定的fagment要全路径

2、方式二:在Activity动态添加

在Java文件中进行动态添加

// 自定一个的Fragment文件
 BlankFragment blankFragment = new BlankFragment();
 FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
 // android.R.id.content是系统内置的,直接添加到Activity中
 fragmentTransaction.add(android.R.id.content, blankFragment);
 // 提交
 fragmentTransaction.commit();

上述有个问题是:使用内置的属性添加会浮在上层,与原来在Activity文件中的内容重叠
在这里插入图片描述
解决该问题可以在xml文件创建FrameLayout标签并添加id
在这里插入图片描述

并在Java代码中将原来设置的内置的id进行修改为自定义的FrameLayout的id
在这里插入图片描述
这样就正常填充到FrameLayout的位置中,而不是重叠
在这里插入图片描述

实例

1、实现类似微信等底部点击tab然后显示不同的功能页面,如下
在这里插入图片描述

2、activity_main.xml

<?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=".MainActivity">

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

    <GridLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:columnCount="2"
        >

        <LinearLayout
            android:id="@+id/index_tabBar"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:paddingTop="10dp"
            android:paddingBottom="10dp"
            android:orientation="vertical"
            android:gravity="center_horizontal"
            android:layout_columnWeight="1"
            >
            <ImageView
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:src="@mipmap/index_tab"
                ></ImageView>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="主页"
                ></TextView>
        </LinearLayout>

        <LinearLayout
            android:id="@+id/my_tabBar"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:paddingTop="10dp"
            android:paddingBottom="10dp"
            android:orientation="vertical"
            android:gravity="center_horizontal"
            android:layout_columnWeight="1"
            >
            <ImageView
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:src="@mipmap/my_tab"
                ></ImageView>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="我的"
                ></TextView>
        </LinearLayout>

    </GridLayout>

</LinearLayout>

3、fragment_index.xml:主页对应的fragment

<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context=".Index">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Index Fragment" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/index_tab"
        ></ImageView>

</FrameLayout>

4、fragment_my.xml:“我的”对应xml

<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context=".My">
    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="My Fragment" />
</FrameLayout>

5、MainActivity.java

package com.example.fragment_switch_page;

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

import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//      获取点击的域
        LinearLayout indexL = findViewById(R.id.index_tabBar);
        LinearLayout myL = findViewById(R.id.my_tabBar);

//      通过FrameLayout布局,初始是没有页面的,所以手动设置主页为首页
        setIndex();

//      “主页”和“我的”的监听事件
        indexL.setOnClickListener(onClickListener);
        myL.setOnClickListener(onClickListener);
    }
//  设置主页
    public void setIndex(){
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        Index index = new Index();
        ft.add(R.id.tabBars_fragment, index);
        ft.commit();

    }

//  统一的监听器
    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            FragmentManager fm = getSupportFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();
            Fragment fragment = null;

            switch (view.getId()){
                case R.id.index_tabBar:
                    fragment = new Index();
                    break;
                case R.id.my_tabBar:
                    fragment = new My();
                    break;
            }
//          fragment之间进行覆盖并设置切换效果
            ft.replace(R.id.tabBars_fragment, fragment, "fragment").setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE).commitAllowingStateLoss();
//            ft.commit();

        }
    };
}

6、Index.java:“主页”fragment相关联的Java文件

package com.example.fragment_switch_page;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

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

public class Index extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

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

//  可以通过该方法配置一个设置了参数的fragment,具体的参数可自行定义
    public static Index newInstance(String param1, String param2) {
        Index fragment = new Index();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
//          获取配置的参数
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
//      绑定布局文件到这个fragment
        return inflater.inflate(R.layout.fragment_index, container, false);
    }
}

7、My.java:“我的”相关联的Java文件

package com.example.fragment_switch_page;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

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

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link My#newInstance} factory method to
 * create an instance of this fragment.
 */
public class My extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

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

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment My.
     */
    // TODO: Rename and change types and number of parameters
    public static My newInstance(String param1, String param2) {
        My fragment = new My();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_my, container, false);
    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值