使用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 ...
随机推荐
- ERP入门
为什么想起写这个题目哪?其实这个问题很久就想写了,记得2005年时候,公司新招的二位刚毕业的大学生,一个专业是经济管理,一个是会计,东北大区培训后公司让我选择了一位带一带,我选择了一个会计专业的(因为 ...
- App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file
ios进行http请求,会出现这个问题: App Transport Security has blocked a cleartext HTTP (http://) resource load sin ...
- 进新公司用cornerstone-checkout后遇到的奇葩bug,及解决方法
从cornerstone中checkout下新的工程,运行报错. 1.开始错误原因是找不到相对应的某个.m文件的路径 解决方案:将缺少的.m文件重新从项目文件夹中导入 2.后来显示 造成的原因是在下面 ...
- rails中的session
学rails toturial的时候,第八章一直觉得有点没吃透,后来看了两篇rails关于session和cookies源码分析的文章,cookie原理与实现(rails篇) 和session原理与实 ...
- DbVisualizer连接hbase
1.添加phoneix驱动 (1).点击Tools--->Driver Manager- (2).新建一个驱动,名称为phoenix(名称随意),选择phoenix的客户端驱动,驱动类如图所示 ...
- [Java入门笔记] 面向对象三大特征之:继承
理解什么是继承 首先我们知道,面对对象有三大特征: 封装:解决了数据的安全性问题 继承:解决了代码的重用问题 多态:解决了程序的扩展问题 上一篇博客中,我们了解了一下封装,现在我了再来看看什么是继承. ...
- spring security oauth2.0 实现
oauth应该属于security的一部分.关于oauth的的相关知识可以查看阮一峰的文章:http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html ...
- 【Windows编程】系列第十一篇:多文档界面框架
前面我们所举的例子中都是单文档界面框架,也就是说这个窗口里面的客户区就是一个文档界面,可以编写程序在里面输入或者绘制文本和图形输出,但是不能有出现多个文档的情况.比如下面的UltraEdit就是一个典 ...
- 【小白的CFD之旅】06 流体力学基础
从黄师姐那里了解到要学习CFD的话,需要先补充流体力学.数学以及计算机方面的常识,小白就一阵头大.想起当初自己已经把牛皮吹出去了,现在都不知道怎么收场,一个月入不了门多丢人.不过头大归头大,小白还是老 ...
- maven私服搭建
一.软件安装 地址:http://www.sonatype.org/nexus/thank-you-for-downloading/?dl=tgz 解压: 启动: >> nexus sta ...
