使用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 ...
随机推荐
- Java线程
线程 线程 线程(Thread)是控制线程(Thread of Control)的缩写,是程序运行的基本单位,它是具有一定顺序的指令序列(即所编写的程序代码).存放方法中定义局部变量的栈和一些共享数据 ...
- 使用原生JS实现一个风箱式的demo,并封装了一个运动框架
声明,该DEMO依托于某个培训机构中,非常感谢这个培训结构.话不多说,现在开始改demo的制作. 首先,在前端的学习过程中,轮播图是我们一定要学习的,所以为了更加高效的实现各种轮播图,封装了一个运动的 ...
- 隐式启动判断是否有匹配的Intent
一.PackageManager的resolveActivity public abstract ResolveInfo resolveActivity(Intent intent, int flag ...
- iOS 陀螺仪,加速度计
atan2(x, y)反正切函数 x是对边 y临边 data.acceleration 加速度值,当手机水平放置时值为(0,0,-1),当手机竖直放置时值为(0,-1,0),判断手机拿起状态可以 ...
- sql 截取日期
截取日期: select to_char( NEW_TIME( sysdate, 'GMT','EST'), 'yyyy-mm')from dual; 或得年或月或日 Year/ month/Da ...
- yum安装mysql和mysql源,配置mysql
申明,不要用root安装 1. 下载mysql的repo源 $ wget http://repo.mysql.com/mysql-community-release-el7-5.noarch.rpm ...
- Redhat Server 5.7 安装配置PHP
PHP的简介 PHP于1994年由Rasmus Lerdorf创建,刚刚开始是Rasmus Lerdorf 为了要维护个人网页而制作的一个简单的用Perl语言编写的程序.这些工具程序用来显示 Rasm ...
- TCP三次握手建立连接
基本过程: ISN(初始序号)随时间变化,每一个连接具有不同的ISN,防止在网络延迟中分组被重新发送. 请求端发送SYN(同步序号 )=1,seq=ISN(32bits序号,每4ms+ ...
- SQL Update:使用一个表的数据更新另一张表
表结构 功能 用表B的数据(mc列)更新表A的mc列 SQL Server update A SET A.mc = b.mc FROM A ,B WHERE A.bmbh = B.bmbh and A ...
- SQL Server 2008 R2——统计各部门某年入职人数
=================================版权声明================================= 版权声明:原创文章 谢绝转载 请通过右侧公告中的“联系邮 ...
