使用Fragment创建灵活的用户界面
什么是Fragment
Fragment的作用像Activity一样,主要用于呈现用户界面,它依附于Activity存在,但比Activity更灵活。
当我们需要创建动态的,多面板的界面的时候就需要使用Fragment。
继承Fragment类
继承Fragment类,并覆盖相应的方法,就可以实现自己的Fragment类。 但是Fragment类是在Android 3.0添加的。
要在低于这个版本下使用Fragment,就需要导入v7 appcompat库。另外,Fragment的容器必须是FragmentActivity,
ActionBarActivity也可以,因为它继承于FragmentActivity。
在使用ActionBarActivity的时候,要想程序正常运行,程序的主题必须基于Theme.AppCompact,否则,程序崩溃。
如下:
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/Theme.AppCompat.Light" >
<activity
android:name="com.whathecode.usingfragment.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
程序布局:

示例代码
TitleFragment:
package com.whathecode.usingfragment; import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup; public class TitleFragment extends Fragment
{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
return inflater.inflate(R.layout.thetitle, container, false);
}
}
ContentFragment:
package com.whathecode.usingfragment; import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup; public class ContentFragment extends Fragment
{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
return inflater.inflate(R.layout.thecontent, container, false);
}
}
上面两个Fragment类的代码基本一样,只是使用了不同的布局界面。
和Activity不一样的,Fragment是在onCreateView方法中嵌入界面,而Activity是在onCreate方法中使用setContentView方法设置界面布局。
activity_main界面代码
<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:orientation="horizontal"
tools:context=".MainActivity" > <LinearLayout
android:id="@+id/titleC"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="fill_parent"
android:orientation="vertical"/> <LinearLayout
android:id="@+id/contentC"
android:layout_width="0dp"
android:layout_weight="2"
android:layout_height="fill_parent"
android:orientation="vertical"/> </LinearLayout>
材料都准备好后,最后一步就是将Fragment添加到Activity上面
package com.whathecode.usingfragment; import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity; public class MainActivity extends ActionBarActivity
{ @Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); /**
* 使用FragmentTransaction中的add方法将Fragment嵌入到当前的Activity上
*/
FragmentManager supportFragmentManager = getSupportFragmentManager(); FragmentTransaction transaction = supportFragmentManager.beginTransaction(); //嵌入TitleFragment
transaction.add(R.id.titleC, new TitleFragment()); /**
* 当所有的事务完成之后才能调用commit方法。
* commit方法不能多次调用,否则程序崩溃
*/ //嵌入ContentFragment
transaction.add(R.id.contentC, new ContentFragment()).commit();
}
}
运行效果:
Fragment间通讯
既然,Fragment是依附在Activity上面,那么它必然也是通过Activity作为媒介进行通讯。
假如我想在TitleFragment中获取ContentFragment中的内容,可以这样做:
1. 通过getActivity获得当前Activity的实例
2. 通过Activity的findViewById方法取得想要获取的View
示例代码:
package com.whathecode.usingfragment; import android.os.Bundle;
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 TitleFragment extends Fragment
{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
return inflater.inflate(R.layout.thetitle, container, false);
} @Override
public void onStart()
{
super.onStart(); //获取界面中的Button按钮
Button btn = (Button) getActivity().findViewById(R.id.getContent); //绑定onClick事件
btn.setOnClickListener(new View.OnClickListener()
{ @Override
public void onClick(View v)
{ //获取ContentFragment布局中的textView
TextView txtView = (TextView) getActivity().findViewById(
R.id.content); //获取TextView中的文本内容
String content = txtView.getText().toString(); //显示内容
Toast.makeText(getActivity(), content, Toast.LENGTH_SHORT)
.show();
}
});
}
}
运行结果:

当然,这只是其中一种方法,也是不怎么好的方法。官方建议是在Fragment中定义一个接口,然后由Activity容器实现这个接口。
改良后的代码:
在TitleFragment中添加接口
package com.whathecode.usingfragment; import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup; public class TitleFragment extends Fragment
{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
return inflater.inflate(R.layout.thetitle, container, false);
} /**
*
* @author Administrator
*新添加的接口,由Activity实现
*/
public interface onGetContentListener
{
public void onGetContent();
}
}
实现接口:
package com.whathecode.usingfragment; import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast; public class MainActivity extends ActionBarActivity implements
TitleFragment.onGetContentListener
{
FragmentManager supportFragmentManager = getSupportFragmentManager();
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); /**
* 使用FragmentTransaction中的add方法将Fragment嵌入到当前的Activity上
*/ FragmentTransaction transaction = supportFragmentManager
.beginTransaction(); // 嵌入TitleFragment
transaction.add(R.id.titleC, new TitleFragment()); /**
* 当所有的事务完成之后才能调用commit方法。 commit方法不能多次调用,否则程序崩溃
*/ // 嵌入ContentFragment
transaction.add(R.id.contentC, new ContentFragment()).commit();
} /**
* 只能在Fragment被嵌入到Activity后才能获取Fragment中的控件
* 因此这里在onStart方法中实现逻辑代码
*/
@Override
protected void onStart()
{
super.onStart(); Button btn = (Button) findViewById(R.id.getContent); btn.setOnClickListener(new View.OnClickListener()
{ @Override
public void onClick(View v)
{
onGetContent();
}
});
} /**
* 实现TitleFragment中内部接口的方法
*/
@Override
public void onGetContent()
{
TextView txtView = (TextView) findViewById(R.id.content);
Toast.makeText(this, txtView.getText().toString(), Toast.LENGTH_SHORT).show();
}
}
运行效果和之前的一样,只是把逻辑都移到了Activity上
使用Fragment创建灵活的用户界面的更多相关文章
- 【译】用Fragment创建动态的界面布局(附Android示例代码)
原文链接:Building a Dynamic UI with Fragments 为了在Android上创建一个动态和多视图的用户界面,你需要封装UI控件和模块化Activity的行为,以便于你能够 ...
- Android 用Fragment创建一个选项卡
本文结合之前的动态创建fragment来进行一个实践,来实现用Fragment创建一个选项卡 本文地址:http://www.cnblogs.com/wuyudong/p/5898075.html,转 ...
- 编写利用Fragment创建新闻列表
编写利用Fragment创建新闻列表 1.创建新闻实体类News,代码如下: public class News { private String title; private String co ...
- java 添加一个线程、创建响应的用户界面 。 演示示例代码
javajava 添加一个线程.创建响应的用户界面 . 演示示例代码 来自thinking in java 4 21章 部分的代码 夹21.2.11 thinking in java 4免费下载: ...
- Android UI开发第三十篇——使用Fragment构建灵活的桌面
http://www.lupaworld.com/article-222973-1.html 当我们设计应用程序时,希望能够尽最大限度的适配各种设备,包括4寸屏.7寸屏. 10寸屏等等,Android ...
- Android Fragment详解(二):Fragment创建及其生命周期
Fragments的生命周期 每一个fragments 都有自己的一套生命周期回调方法和处理自己的用户输入事件. 对应生命周期可参考下图: 创建片元(Creating a Fragment) To c ...
- android 之fragment创建
1.使用xml标签 1.1定义两个重要属性 <fragment android:id="@+id/fregment_top" android: ...
- Xamarin.Forms入门-使用 Xamarin.Forms 来创建跨平台的用户界面
Xamarin.Forms 是一个跨平台的.基于原生控件的UI工具包,开发人员可以轻松的创建适用于 Android,iOS 以及 Windows Phone的用户界面.Xamarin.Forms 通过 ...
- Fragment 创建 传递参数 跳转 典例
抽取的控制Fragment的父Activity /** * 抽象一个Activity托管我们的Single Fragment */ public abstract class SingleFrag ...
随机推荐
- SharePoint 2013 工作流平台的选项不可用
问题描述 当我想创建一个SharePoint 2013 工作流的时候,打开SharePoint 2013 Designer(一下简称SPD),发现没有SharePoint 2013 工作流的选项.原来 ...
- IOS开发基础知识--碎片22
1:设置有间距的表格行(UITableViewStyleGrouped) .设置section的数目,即是你有多少个cell - (NSInteger)numberOfSectionsInTableV ...
- iOS数字键盘自定义按键
UIKeyboardTypeNumberPad 数字键盘自定义按键 最近做一个搜索用户的功能,这里使用了UISearchBar.由于搜索的方式只有手机号码,所以这里的键盘要限制为数字输入,可以这么做: ...
- Git Learning - By reading ProGit
Today I begin to learn to use Git. I learn from Pro Git. And I recommend it which is an excellent bo ...
- centos6.5和centos7如何搭建php环境
作者:白狼 出处:http://www.manks.top/linux_php.html 本文版权归作者,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责 ...
- java实现REST方式的webService
一. 简介 WebService有两种方式,一是SOAP方式,二是REST方式.SOAP是基于XML的交互,WSDL也是一个XML文档, 可以使用WSDL作为SOAP的描述文件:REST是基于HTTP ...
- Linux的主机规划和磁盘分区
选择与Linux搭配的主机配置 CPU 只要不是老旧到让你的硬件系统死机的都能够支持 RAM 内存越大越好,内存的重要性要比CPU还要高,至少512MB Hard Disk 由于数据量与数据的访问频 ...
- mycat高可用方案
1.建议采用标准的mysql主从复制高可用配置并交付给mycat来完成后端mysql节点的主从自动切换. 2.mycat自身的高可用性 由HAproxy+Mycat集群+Mysql主从所组成的高可用性 ...
- CentOS使用yum源中自带的rpm包安装LAMP环境
CentOS使用yum源中自带的rpm包安装LAMP环境.这是Linux下安装LAMP的环境一种最基本最简便的方式.新手可以从容安装使用. 1. 安装基础包(可选安装)yum install -y w ...
- 无需FQ,自建本地CDN,秒上StackOverFlow!
StackOverflow是一个面向程序员的技术问答平台.可是在不FQ的情况下,浏览StackOverflow是一件让人极不舒服的事情,常常需要等待数十秒页面才慢慢显示出来.本文我教大家一种能够流畅地 ...
