Android学习之Fragment的使用

Android中Fragment的使用

  首先,我们了解一下使用Activity遇到的问题?
  ·Activity和对应界面往往不易分离(含控件管理代码);
  ·导致Activity和界面资源的重用性变差;
  ·需要一个能够容纳多个界面并对界面编程的中间层。

  为什么使用Fragment?
  在Android 3.0之前的版本,通常程序运行在较小屏幕的设备上,随着技术的发展,Android开始支持平板电脑,相比手机大了很多,若还是像手机那样只显示联系人列表,显的操控不够自然,同时也不能很好地体现大尺寸屏幕的优点。手机程序是通过不同的窗口显示不同级别的信息,而平板电脑程序会尽可能利用当前界面的显示更多的信息。对于同时适应手机和平板电脑的APK程序比较麻烦,为了解决这个问题,就需要一种可以式布局、共享以及控制的通用式系统。
  Fragment是Android3.0新增加的概念:
  ·同Activity类似,建立用来和用户交互的界面;
  ·可以在一个Activity中建立多个UI面板;
  ·也可以在多个Activity中重用Fragment。

  ☆☆☆Android Studio实现静态使用Fragment
  1.打开Android Studio,新建工程后,在layout文件夹下新建两个名为fragment1.xml、fragment2.xml的布局文件。

<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="com.example.a96349.fragmenttest.Fragment1">
    
    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="这是第一个Fragment"
        android:background="@android:color/holo_orange_dark"
        android:textColor="@android:color/holo_red_dark" />
        
</FrameLayout>
<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="com.example.a96349.fragmenttest.Fragment2">
    
    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="这是第二个Fragment"
        android:background="@android:color/holo_green_dark"
        android:textColor="@android:color/holo_red_dark" />
        
</FrameLayout>

  2.新建两个类Fragment1、Fragment2,都继承自Fragment。

package com.example.a96349.fragmenttest;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Fragment1 extends Fragment {
    public Fragment1() {
        // Required empty public constructor
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment1, container, false);
    }
    
}
package com.example.a96349.fragmenttest;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Fragment2 extends Fragment {
    public Fragment2() {
        // Required empty public constructor
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment2, container, false);
    }
    
}

  3.打开activity_main.xml作为主Activity的布局文件,在里面加入两个Fragment的引用,使用android:name前缀来引用具体的Fragment。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.a96349.fragmenttest.MainActivity">
    
    <fragment
        android:id="@+id/fg1"
        android:name="com.example.a96349.fragmenttest.Fragment1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"/>
    <fragment
        android:id="@+id/fg2"
        android:name="com.example.a96349.fragmenttest.Fragment2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"/>
        
</LinearLayout>

  4.MainActivity作为程序的主Activity。

package com.example.a96349.fragmenttest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {

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

  运行结果:
  在这里插入图片描述

  Fragment真正的强大之处在于可以动态地添加到Activity,如何动态添加Fragment呢?在静态的Fragment的基础上修改,打开activity_main.xml,将其中对Fragment的引用都删除,只保留最外层的LinearLayout,并给它添加一个id,因为我们要动态添加Fragment,不用在XML里添加了。
  ☆☆☆Android Studio实现动态使用Fragment
  1.打开Android Studio,新建工程后,在layout文件夹下新建两个名为fragment_blank_fragment1.xml、fragment_blank_fragment2.xml的布局文件。

<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="com.example.a96349.fragment.BlankFragment1">
    
    <!-- TODO: Update blank fragment layout -->
    
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        
        <Button
            android:text="Fragment1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/button"
            android:textAllCaps="false"
            android:textColor="@android:color/holo_red_dark" />
            
        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="这是第一个Fragment"
            android:textColor="@android:color/holo_red_dark"
            android:background="@android:color/holo_orange_dark" />
            
    </LinearLayout>
    
</FrameLayout>
<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="com.example.a96349.fragment.BlankFragment2">
    
    <!-- TODO: Update blank fragment layout -->
    
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        
        <Button
            android:text="Fragment2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/button2"
            tools:text="Fragment2"
            android:textAllCaps="false"
            android:textColor="@android:color/holo_red_dark" />
            
        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="这是第二个Fragment"
            tools:textColor="@android:color/holo_red_dark"
            android:background="@android:color/holo_green_dark" />
            
    </LinearLayout>
    
</FrameLayout>

  2.新建两个类BlankFragment1、BlankFragment2,都继承自Fragment,并通过Button来提示。

package com.example.a96349.fragment;

import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

public class BlankFragment1 extends Fragment {
    public BlankFragment1() {
        // Required empty public constructor
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_blank_fragment1, container, false);
    }
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Button bt=(Button)getActivity().findViewById(R.id.button);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getActivity(),"Fragment1",Toast.LENGTH_LONG).show();
            }
        });
    }
}
package com.example.a96349.fragment;

import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

public class BlankFragment2 extends Fragment {

    public BlankFragment2() {
        // Required empty public constructor
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_blank_fragment2, container, false);
    }
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Button bt=(Button)getActivity().findViewById(R.id.button2) ;
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getActivity(),"Fragment2",Toast.LENGTH_LONG).show();
            }
        });
    }
}

  3打开activity_main.xml,给LinearLayout添加一个id。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.a96349.fragment.MainActivity">
    
</RelativeLayout>

  4.MainActivity作为程序的主Activity。

package com.example.a96349.fragment;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Display;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Display dp=getWindowManager().getDefaultDisplay();
        if (dp.getWidth()<dp.getHeight()){
            BlankFragment1 bf1=new BlankFragment1();
            getFragmentManager().beginTransaction().replace(R.id.activity_main,bf1).commit();
        }else {
            BlankFragment2 bf2=new BlankFragment2();
            getFragmentManager().beginTransaction().replace(R.id.activity_main,bf2).commit();
        }
    }
    
}

  运行结果:
  在这里插入图片描述  在这里插入图片描述

  Fragment的存在必须要要依附于Activity,FragmentActivity是继承Activity的。Fragment和Fragment之间的通讯的桥梁是FragmentManager类,用来管理所有的Fragment的,所以可以找到任何一个所需要的Fragment类。
  Activity一般都会包含多个Fragment,这时多个Fragment之间如何进行通信就是个非常重要的问题。我们通过一个实例来说明一个Fragment中去访问另一个Fragment的视图。
  ☆☆☆Android Studio实现一个Fragment中去访问另一个Fragment的视图
  1.打开Android Studio,新建工程后,在layout文件夹下新建两个名为fragment1.xml、fragment2.xml的布局文件,在fragment1.xml文件中添加一个TextView,并添加id,在fragment2.xml文件中添加一个TextView和Button。

<?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"
    android:background="@android:color/holo_green_dark"
    tools:context="lession.example.com.learnfragment.Fragment1">
    
    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="这是第一个Fragment"
        android:textColor="@android:color/holo_red_dark"
        android:textSize="20sp"
        android:id="@+id/textView" />
        
</FrameLayout>
<?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"
    android:background="@android:color/holo_orange_dark"
    tools:context="lession.example.com.learnfragment.Fragment2">
    
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        
        <TextView
            android:text="这是第二个Fragment"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/textView2"
            android:textSize="20sp"
            android:textColor="@android:color/holo_red_dark" />
            
        <Button
            android:text="获取fragment1的信息"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/button"
            android:textAllCaps="false"
            android:background="@android:color/holo_purple"
            android:textSize="20sp"
            android:textColor="@android:color/holo_red_dark" />
    </LinearLayout>
    
</FrameLayout>

  2.新建两个类Fragment1、Fragment2,都继承自Fragment,在Fragment2.java中添加onActivityCreated方法,并处理按钮的点击事件。

package lession.example.com.learnfragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Fragment1 extends Fragment {

    public Fragment1() {
        // Required empty public constructor
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment1, container, false);
    }
    
}
package lession.example.com.learnfragment;

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.Button;
import android.widget.TextView;
import android.widget.Toast;

public class Fragment2 extends Fragment {

    public Fragment2() {
        // Required empty public constructor
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment2, container, false);
    }
    
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Button bt = (Button) getActivity().findViewById(R.id.button);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TextView textView = (TextView) getActivity().findViewById(R.id.textView);
                Toast.makeText(getActivity(),textView.getText(),Toast.LENGTH_LONG).show();
            }
        });
    }
    
}

  3.打开activity_main.xml作为主Activity的布局文件,在里面加入两个Fragment的引用,使用android:name前缀来引用具体的Fragment。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:baselineAligned="false">
    
    <fragment
        android:id="@+id/fg1"
        android:name="lession.example.com.learnfragment.Fragment1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"/>
        
    <fragment
        android:id="@+id/fg2"
        android:name="lession.example.com.learnfragment.Fragment2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"/>
        
</LinearLayout>

  4.MainActivity作为程序的主Activity。

package lession.example.com.learnfragment;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    
}

  运行结果:点击按钮
  在这里插入图片描述
  这就是Fragment的使用,如果转载以及CV操作,请务必注明出处,谢谢!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值