Android -- 使用Fragment

Fragment类似与Activity,可以使用它进行多个页面间的切换(A页面跳转到B页面),之前我们了解过,通过Activity也可以实现这样的操作(http://blog.csdn.net/gaopeng0071/article/details/45043967)。那为什么会出现Fragment呢,下面我们来看看

Fragment介绍

Android运行在各种各样的设备中,有小屏幕的手机,超大屏的平板甚至电视。针对屏幕尺寸的差距,很多情况下,都是先针对手机开发一套App,然后拷贝一份,修改布局以适应平板神马超级大屏的。难道无法做到一个App可以同时适应手机和平板么,当然了,必须有啊。Fragment的出现就是为了解决这样的问题。你可以把Fragment当成Activity的一个界面的一个组成部分,甚至Activity的界面可以完全有不同的Fragment组成,更帅气的是Fragment拥有自己的生命周期和接收、处理用户的事件,这样就不必在Activity写一堆控件的事件处理的代码了。更为重要的是,你可以动态的添加、替换和移除某个Fragment。

可以简单理解,就是Fragment相对Activity更轻量级、效率更高、速度更快

下面我们来看一个简单跳转例子。

我们来看下工程布局

1个Activity,2个Fragment,以及所对应的xml资源文件。

下面我们看代码MainActivity

package gp.com.learnfragment;

import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if(savedInstanceState == null){
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment, new MainActivityFragment()).commit();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

代码16到19行将目标Fragment添加到容器中。

下面来看MainActivityFragment

package gp.com.learnfragment;

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

/**
 * A placeholder fragment containing a simple view.
 */
public class MainActivityFragment extends Fragment {

    public MainActivityFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main, container, false);

        view.findViewById(R.id.showOthFragment)
                .setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getFragmentManager().beginTransaction()
                        .replace(R.id.fragment, new OtherFragment())
                        .commit();
            }
        });

        return view;
    }
}

注意onCreateView方法,其中为showOthFragment按钮增加了跳转到另外一个Fragment的事件。

Fragment_main.xml代码:

<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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:orientation="vertical"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivityFragment">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="呈现另一个fragment"
        android:id="@+id/showOthFragment" />

</LinearLayout>

其中包含showOthFragment按钮

OtherFragment类代码

package gp.com.learnfragment;

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

/**
 * Created by zm on 2015/7/14.
 */
public class OtherFragment extends Fragment {
    public OtherFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_other, container, false);
    }
}

Fragment_other.xml代码

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="我是另外一个fragment页面"
        android:id="@+id/textView" />
</LinearLayout>

至此一套简易的Fragment代码构建用法完成。

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-07-31 23:39:23

Android -- 使用Fragment的相关文章

android基础----&gt;Fragment的使用

碎片(Fragment)是一种可以嵌入在活动当中的UI 片段,它能让程序更加合理和充分地利用大屏幕的空间,因而在平板上应用的非常广泛. Fragment的基础例子 一.增加Fragment,another_right_fragment.xml文件: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"

Android——ViewPager+Fragment+ListView之间

Android--ViewPager+Fragment+ListView之间 <span style="font-size:18px;">package com.example.jreduch05; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.support.v7.app.A

[转]android.support.v4.app.Fragment和android.app.Fragment区别

1.最低支持版本不同 android.app.Fragment 兼容的最低版本是android:minSdkVersion="11" 即3.0版 android.support.v4.app.Fragment 兼容的最低版本是android:minSdkVersion="4" 即1.6版 2.需要导jar包 fragment android.support.v4.app.Fragment 需要引入包android-support-v4.jar 3.在Activity

Android之fragment生命周期解析

上篇讲到了Fragment的基础应用,现在给大家演示一下Fragment的生命周期是什么样子的.关于Fragemnt的基础应用,请见http://blog.csdn.net/jiapeng2b/article/details/46919859. 一.首先,我们先看一下Fragment的生命周期 跟Activity生命周期的对比 Activity直接影响它所包含的fragment的生命周期,所以对activity的某个生命周期方法的调用也会产生对fragment相同方法的调用.例如:当activi

Android 隐藏Fragment

1.隐藏Fragment FragmentManager fManager = getFragmentManager(); fManager.beginTransaction() .setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out) .show(yourFragmentName).commit(); fManager.beginTransaction().remove(mMangerFragme

Android之Fragment用法

本文翻译自Android developer网站上面,原文参考:Building a Dynamic UI with Fragments 当我们需要动态的多界面切换的时候,就需要将UI元素和Activity融合成一个模块.在2.3中我们一般通过各种Activity中进行跳转来实现多界面的跳转和单个界面动态改变.在4.0或以上系统中就可以使用新的特性来方便的达到这个效果--Fragment类.Fragment类似一个嵌套Activity,可以定义自己的layout和自己的生命周期. 多个Fragm

android之fragment的使用

android中的fragment与html中的iframe很类似,下图中通过左边的按键可以控制右边的显示内容 工程目录 需要定义三个fragment类,每个类中显示不同的内容,每个fragment对应一个布局文件 布局文件 在主布局文件定义按钮和帧布局 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.co

android开发 Fragment嵌套调用常见错误

在activity中有时需要嵌套调用fragment,但嵌套调用往往带来视图的显示与预期的不一样或是fragment的切换有问题.在使用时要注意几点: 1.fragment中嵌套fragment,子fragment视图无法显示: 如下: 父fragment的.xml文件: <pre name="code" class="html"><LinearLayout xmlns:android="http://schemas.android.co

android之Fragment基础详解(一)

一.Fragment的设计哲学 Android在3.0中引入了fragments的概念,主要目的是用在大屏幕设备上--例如平板电脑上,支持更加动态和灵活的UI设计.平板电脑的屏幕比手机的大得多,有更多的空间来放更多的UI组件,并且这些组件之间会产生更多的交互. 针对屏幕尺寸的差距,很多情况下,都是先针对手机开发一套App,然后拷贝一份,修改布局以适应平板神马超级大屏的.难道无法做到一个App可以同时适应手机和平板么,当然了,必须有啊.Fragment的出现就是为了解决这样的问题.你可以把Frag

Android ViewPager Fragment使用懒加载提升性能

?? Android ViewPager Fragment使用懒加载提升性能 Fragment在如今的Android开发中越来越普遍,但是当ViewPager结合Fragment时候,由于Android ViewPager内在的加载机制,导致一个比较严重的加载性能问题,具体来说,假设一个ViewPager中有n多个Fragment,那么ViewPager在初始化阶段将一次性的初始化FragmentPagerAdapter中的至少3个Fragment(如果Fragment多于3),创建和加载Fra