---
title: "Fragment"
author: "Java-Object"
date: "2013-06-01T02:35:47Z"
tags: []
categories: ["编程语言"]
slug: "fragment"
draft: false
lastmod: "2013-07-03T16:45:08Z"
id: 1880845
url: "https://hezd.iteye.com/blog/1880845"
---

fragment自定义片段

手机屏幕上显示两个Activity，在平板电脑上时两个Activity显示的内容可以在一个界面上显示出来。不同屏幕和不同分别率显示的效果。

 

在手机屏幕上创建两个Activity，而在平板电脑上显示一个Activity显示手机屏幕两个Activity的内容。

 

优点：创建新的界面时不需要在去创建activity，Fragment不需要在清单文件中配置，简化了开发过程，

注意：Fragment在3.0以上版本上才可以使用。

 

Fragment使用

1.创建fragment，创建两个类继承Fragment，与布局文件中的两个fragment标签相对应。这个类类似于小的Activity，activity需要在清单文件中配置，fragment需要在布局文件中配置。类的全名称配置到布局文件中的fragment中的name属性的值。

2.创建两个fragment的布局文件。设置fragment要显示的内容。

3.使用Fragment，在布局文件中增加两个fragment标签，首字母小写。

  首字母大小表示一种view对象，小写开头表示一种类型。

  Name属性指定显示内容，fragment真正显示的时候加载的哪一个类。Name指定的是我  们要写的一个fragment的全路径名称。

4.与activity的oncreate方法类似，oncreateview，当fragment被初始化要显示里面的内容时调用。返回值是view对象，返回给界面让界面去显示他里面要展示的内容

 Oncreateview方法的参数，

inflate填充器填充一个布局文件指定fragment要显示的内容

Groupview，fragment要加载到那个界面里

attachToRoot，是否直接挂载到父节点上，一般设置为false。

 

 

总结：

创建类继承Fragment，当布局文件中的fragment被初始化时会找到指定的fragment类，fragment类的oncreateview方法会将fragment要显示的内容利用填充器填充一个布局文件为一个view对象，最终显示在屏幕上。

 

 

应用场景：

如下图在，屏幕左边创建一个listview，右边创建fragment，当点击listview中条目时，动态修改右边界面的内容，右边界面内容使用fragment显示。

 

 

 

 

 

 

 

 

Android-support-v4.jar：提供向低版本的api的兼容。

 

如何开发一个fragment程序既可以适配高版本4.0又可以适配低版本2.3 ？

在项目的libs目录下有一个支持jar包android-support-v4.jar，使用其中的类可以适配不同的版本。

1.使用新特性的类时，导包时使用android.support.v4.app支持jar包中的类。

2.Activity要继承FragmentActivity

 

--------------------------------布局文件-----------------------

主界面布局文件MainActivity.xml

&lt;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"

    tools:context=".MainActivity" &gt;

 

    &lt;fragment

        android:id="@+id/fragment1"

        android:name="com.itheima.fragment.Fragment1"

        android:layout\_width="0dip"

        android:layout\_height="match\_parent"

        android:layout\_weight="1" /&gt;

 

    &lt;fragment

        android:id="@+id/fragment2"

        android:name="com.itheima.fragment.Fragment2"

        android:layout\_width="0dip"

        android:layout\_height="match\_parent"

        android:layout\_weight="1" /&gt;

 

&lt;/LinearLayout&gt;

 

Fragment1布局文件

&lt;?xml version="1.0" encoding="utf-8"?&gt;

&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout\_width="match\_parent"

    android:layout\_height="match\_parent"

    android:background="#660000ff"

    android:orientation="vertical" &gt;

 

    &lt;TextView

        android:layout\_width="wrap\_content"

        android:layout\_height="wrap\_content"

        android:textSize="20sp"

        android:text="我是fragment1的内容" /&gt;

 

&lt;/LinearLayout&gt;

 

Fragment2布局文件

&lt;?xml version="1.0" encoding="utf-8"?&gt;

&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout\_width="match\_parent"

    android:layout\_height="match\_parent"

    android:background="#00ff00"

    android:orientation="vertical" &gt;

 

    &lt;TextView

        android:layout\_width="wrap\_content"

        android:layout\_height="wrap\_content"

        android:textSize="20sp"

        android:text="我是fragment2的内容" /&gt;

 

&lt;/LinearLayout&gt;

 

 

---------------------java文件--------------------

MainActivity.java文件

package com.itheima.fragment;

 

import android.os.Bundle;

import android.app.Activity;

import android.support.v4.app.FragmentActivity;

import android.view.Menu;

 

public class MainActivity extends FragmentActivity {

 

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity\_main);

}

 

}

Fragment1.java文件

package com.itheima.fragment;

 

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 {

@Override

public View onCreateView(LayoutInflater inflater, ViewGroup container,

Bundle savedInstanceState) {

return inflater.inflate(R.layout.fragment1, container, false);

}

}

 

Fragment2.java文件

package com.itheima.fragment;

 

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 {

@Override

public View onCreateView(LayoutInflater inflater, ViewGroup container,

Bundle savedInstanceState) {

return inflater.inflate(R.layout.fragment2, container, false);

}

}

 

 

动态修改Fragment

步骤：

1.创建FragmentManager

2.fragmentManager开始事务，为了保证移除和更新Fragment整个操作要么同时成功要么同时失败。

3.进行替换repalace操作

4.事务提交

 

 

一．当横竖屏切换时，显示不同的Fragment。

MainActivity布局文件

&lt;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"

    tools:context=".MainActivity" &gt;

&lt;/LinearLayout&gt;

 

MainActivity的java文件

package com.company.fragmnet2;

 

import android.os.Bundle;

import android.util.Log;

import android.view.Display;

import android.app.Activity;

import android.app.FragmentManager;

import android.app.FragmentTransaction;

 

public class MainActivity extends Activity {

 

private static final String TAG = "MainActivity";

 

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity\_main);

//获取屏幕的宽和高

Display display = getWindowManager().getDefaultDisplay();

int width = display.getWidth();

int height = display.getHeight();

 

if(width&lt;height) {//如果是竖屏

Log.i(TAG, "竖屏");

FragmentManager fm = getFragmentManager();

FragmentTransaction ft = fm.beginTransaction();

//替换fragment指定容器viewID（也就是它的父窗体），有两种写法一布局文件容器viewid（包含fragment的布局文件R.id.ll\_container)，

//写法二，常用写法android.R.id.content代表当前acitivty容器的id

Fragment1 f1 = new Fragment1();

ft.replace(android.R.id.content, f1);

ft.commit();

}else {//如果是横屏

Log.i(TAG, "横屏");

FragmentManager fm = getFragmentManager();

FragmentTransaction ft = fm.beginTransaction();

Fragment2 f2 = new Fragment2();

ft.replace(android.R.id.content, f2);

ft.commit();

}

}

 

}

 

Fragment1的java文件

package com.company.fragmnet2;

 

import android.app.Fragment;

import android.os.Bundle;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

 

public class Fragment1 extends Fragment{

@Override

public View onCreateView(LayoutInflater inflater, ViewGroup container,

Bundle savedInstanceState) {

return inflater.inflate(R.layout.fragment1\_layout, null);

}

}

 

 

 

二．利用Fragment实现TabHost标签卡界面效果。

创建Fragment步骤：

1.获取Fragment管理器

2.利用FragmentManager开启事务

3.替换内容

4.提交事务

这里标签简单的使用TextView来实现，实际开发时可以使用图片来代替。

 

1.MainActivity布局文件

&lt;RelativeLayout 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=".MainActivity" &gt;

 

    &lt;FrameLayout

        android:id="@+id/container"

        android:layout\_width="match\_parent"

        android:layout\_height="match\_parent" &gt;

    &lt;/FrameLayout&gt;

 

    &lt;LinearLayout

        android:layout\_width="match\_parent"

        android:layout\_height="wrap\_content"

        android:layout\_alignParentBottom="true"

        android:orientation="horizontal" &gt;

 

        &lt;TextView

            android:layout\_width="0dip"

            android:layout\_height="wrap\_content"

            android:layout\_weight="1"

            android:clickable="true"

            android:onClick="click1"

            android:text="功能1" /&gt;

 

        &lt;TextView

            android:layout\_width="0dip"

            android:layout\_height="wrap\_content"

            android:layout\_weight="1"

            android:clickable="true"

            android:onClick="click2"

            android:text="功能2" /&gt;

 

        &lt;TextView

            android:layout\_width="0dip"

            android:layout\_height="wrap\_content"

            android:layout\_weight="1"

            android:clickable="true"

            android:onClick="click3"

            android:text="功能3" /&gt;

    &lt;/LinearLayout&gt;

 

&lt;/RelativeLayout&gt;

 

2.MainActivity的java文件

package com.itheima.fragmenttabhost;

 

import android.os.Bundle;

import android.support.v4.app.FragmentActivity;

import android.support.v4.app.FragmentManager;

import android.support.v4.app.FragmentTransaction;

import android.view.View;

 

public class MainActivity extends FragmentActivity {

 

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity\_main);

 

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

ft.replace(R.id.container, new Fragment1());

ft.commit();

}

 

public void click1(View view) {

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

ft.replace(R.id.container, new Fragment1());

ft.commit();

}

 

public void click2(View view) {

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

ft.replace(R.id.container, new Fragment2());

ft.commit();

}

 

public void click3(View view) {

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

ft.replace(R.id.container, new Fragment3());

ft.commit();

}

}

![](http://dl2.iteye.com/upload/attachment/0085/2934/a3c08d6b-a37d-3a53-9ffd-de8c05f7accc.bmp)  
 

\------------------------------------------

 注意：fragment布局填充的时候使用三个参数的方法去填充否则会报错。

@Override

public View onCreateView(LayoutInflater inflater, ViewGroup container,

Bundle savedInstanceState) {

System.out.println("onCreateView");

return inflater.inflate(R.layout.fragment1, container, false);

}