Fragment是Android3.0新增的概念,是碎片的意思,它和Activity很相像,用来在一个Activity中描述一些行为或部分用户界面;使用多个Fragment可以在一个单独的Activity中建立多个UI面板;Fragment必须被嵌入到Activity中,所的生命周期就跟Activity一样。在Android4.0的设置界面就是左边显示列表,右边显示对应的详细信息,先看下做出来的效果图

这个程序分横竖屏显示,横屏是在一页显示,竖屏分两页显示

首先定义程序中要用到的数据Data.java

package com.example.fragmentdemo;

public final class Data {
// 标题
public static final String[] TITLES = { "声音", "显示", "存储", "电池", "应用程序",
"帐户与同步", "位置服务", "语言和输入法", "备份和重置", "日期与时间" };
// 详细内容
public static final String[] DETAIL = { "显示声音模式", "显示亮度、壁纸、休眠、自动旋转屏幕、字体大小",
"显示机器上SD卡的大小,总容量大小", "显示当前电量", "显示当前安装的应用程序", "显示帐号信息与同步信息",
"显示Google的位置服务、GPS", "显示当前语言信息", "显示备份的数据", "显示当前时间与日期" };
}

定义一个类继承于ListFragment用来显示左边的列表信息

package com.example.fragmentdemo;

import android.app.FragmentTransaction;
import android.app.ListFragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView; public class MyListFragment extends ListFragment {
boolean dualPane; // 是否在一屏上同时显示列表和详细内容 如果为真是横屏,否则竖屏
int curCheckPosition = 0; // 当前选择的索引位置 @Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
System.out.println("MyListFragment-----------onActivityCreated");
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_checked, Data.TITLES)); // 为列表设置适配器 View detailFrame = getActivity().findViewById(R.id.detail); // 获取布局文件中添加的FrameLayout帧布局管理器
dualPane = detailFrame != null
&& detailFrame.getVisibility() == View.VISIBLE; // 判断是否在一屏上同时显示列表和详细内容 if (savedInstanceState != null) {
curCheckPosition = savedInstanceState.getInt("curChoice", 0); // 更新当前选择的索引位置
} if (dualPane) { // 如果在一屏上同时显示列表和详细内容
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); // 设置列表为单选模式 CHOICE_MODE_SINGLE
showDetails(curCheckPosition); // 显示详细内容
}
} // 重写onSaveInstanceState()方法,保存当前选中的列表项的索引值
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curChoice", curCheckPosition);
System.out.println("MyListFragment-----------onSaveInstanceState");
} // 重写onListItemClick()方法
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
System.out
.println("MyListFragment-----------onListItemClick position = "
+ position);
showDetails(position); // 调用showDetails()方法显示详细内容
} void showDetails(int index) {
curCheckPosition = index; // 更新保存当前索引位置的变量的值为当前选中值 if (dualPane) { // 当在一屏上同时显示列表和详细内容时 getListView().setItemChecked(index, true); // 设置选中列表项为选中状态 DetailFragment details = (DetailFragment) getFragmentManager()
.findFragmentById(R.id.detail); // 获取用于显示详细内容的Fragment
if (details == null || details.getShownIndex() != index) { // 如果如果
details = DetailFragment.newInstance(index); // 创建一个新的DetailFragment实例用于显示当前选择项对应的详细内容 // 要在activity中管理fragment, 需要使用FragmentManager
FragmentTransaction ft = getFragmentManager()
.beginTransaction();// 获得一个FragmentTransaction的实例
ft.replace(R.id.detail, details); // 替换原来显示的详细内容
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); // 设置转换效果
ft.commit(); // 提交事务
} } else { // 在一屏上只能显示列表或详细内容中的一个内容时 // 使用一个新的Activity显示详细内容
Intent intent = new Intent(getActivity(),
MainActivity.DetailActivity.class); // 创建一个Intent对象
intent.putExtra("index", index); // 设置一个要传递的参数
startActivity(intent); // 开启一个指定的Activity
}
}
}

右边显示详细信息的Fragment

package com.example.fragmentdemo;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ScrollView;
import android.widget.TextView; public class DetailFragment extends Fragment {
// 创建一个DetailFragment的新实例,其中包括要传递的数据包
public static DetailFragment newInstance(int index) {
DetailFragment f = new DetailFragment(); // 将index作为一个参数传递
Bundle bundle = new Bundle(); // 实例化一个Bundle对象
bundle.putInt("index", index); // 将索引值添加到Bundle对象中
f.setArguments(bundle); // 将bundle对象作为Fragment的参数保存
return f;
} public int getShownIndex() {
return getArguments().getInt("index", 0); // 获取要显示的列表项索引
} @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container == null) {
return null;
} ScrollView scroller = new ScrollView(getActivity()); // 创建一个滚动视图
TextView text = new TextView(getActivity()); // 创建一个文本框对象 text.setPadding(10, 10, 10, 10); // 设置内边距
scroller.addView(text); // 将文本框对象添加到滚动视图中
text.setText(Data.DETAIL[getShownIndex()]); // 设置文本框中要显示的文本
return scroller;
}
}

在主Activity中

package com.example.fragmentdemo;

import android.os.Bundle;
import android.app.Activity;
import android.content.res.Configuration; public class MainActivity extends Activity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
System.out.println("MainActivity-----------onCreate");
} // 创建一个继承Activity的内部类,用于在手机界面中,通过Activity显示详细内容
public static class DetailActivity extends Activity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 判断是否为横屏,如果为横屏,则结束当前Activity,准备使用Fragment显示详细内容
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
System.out.println("MainActivity-----DetailActivity------onCreate");
finish(); // 结束当前Activity
return;
} if (savedInstanceState == null) { //
// 在初始化时插入一个显示详细内容的Fragment
DetailFragment details = new DetailFragment();// 实例化DetailFragment的对象
details.setArguments(getIntent().getExtras()); // 设置要传递的参数
getFragmentManager().beginTransaction()
.add(android.R.id.content, details).commit(); // 添加一个显示详细内容的Fragment
System.out.println("MainActivity-----DetailActivity------onCreate--savedInstanceState == null");
}
}
} }

由于横竖屏的需要,定义两个布局文件

layout->main.xml  竖屏

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:baselineAligned="false"> <fragment class="com.example.fragmentdemo.MyListFragment"
android:id="@+id/titles"
android:layout_weight="1"
android:layout_width="0px"
android:layout_height="match_parent" /> </LinearLayout>

layout_land->main.xml    横屏

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:baselineAligned="false"> <fragment class="com.example.fragmentdemo.MyListFragment"
android:id="@+id/titles"
android:layout_weight="1"
android:layout_width="0px"
android:layout_height="match_parent" /> <FrameLayout android:id="@+id/detail"
android:layout_weight="2"
android:layout_width="0px"
android:layout_height="match_parent"
android:background="?android:attr/detailsElementBackground" /> </LinearLayout>

示例代码

点击打开链接

Android常用控件之Fragment仿Android4.0设置界面的更多相关文章

  1. 编写Java程序,使用Swing布局管理器和常用控件,实现仿QQ登录界面

    返回本章节 返回作业目录 需求说明: 使用Swing布局管理器和常用控件,实现仿QQ登录界面 实现思路: 创建登录界面的类QQLogin,该类继承父类JFrame,在该类中创建无参数的构造方法,在构造 ...

  2. Android4.0设置界面改动总结(三)

    Android4.0设置界面改动总结大概介绍了一下设置改tab风格,事实上原理非常easy,理解两个基本的函数就可以: ①.invalidateHeaders(),调用此函数将又一次调用onBuild ...

  3. Android4.0设置界面改动总结(二)

    今年1月份的时候.有和大家分享给予Android4.0+系统设置的改动:Android4.0设置界面改动总结 时隔半年.回头看看那个时候的改动.事实上是有非常多问题的,比方说: ①.圆角Item会影响 ...

  4. Android常用控件及对应Robotium API

    最近发现Android控件不熟悉,看Robotium的API都费劲. 常用Android控件: 控件类型 描述 相关类 Button 按钮,可以被用户按下或点击,以执行⼀个动作 Button Text ...

  5. 常用的基本控件 android常用控件

    1.TextView:(文本框):不能编辑    android:textColor="@color/tv_show_color" 字体颜色    android:textSize ...

  6. Android常用控件

     Android 中使用各种控件(View) DatePicker - 日期选择控件 TimePicker - 时间选择控件 ToggleButton - 双状态按钮控件 EditText - 可编辑 ...

  7. Android常用控件之GridView使用BaseAdapter

    我们可以为GridView添加自定义的Adapter,首先看下用自定义Adapter的显示效果 在布局文件main.xml文件中定义一个GridView控件 <RelativeLayout xm ...

  8. Android常用控件之RatingBar的使用

    RatingBar控件比较常见就是用来做评分控件,先上图看看什么是RatingBar 在布局文件中声明 <?xml version="1.0" encoding=" ...

  9. android常用控件的使用方法

    引言 xml很强大 TextView <TextView android:id="@+id/text_view" android:layout_width="mat ...

随机推荐

  1. opendrive.com提供的免费网盘

    opendrive.com是由以前freehao123给大家介绍的BOXSTr免费网络硬盘演变而来的,现在BOXSTr已经无法使用了.打开BOXSTr网站就会自动跳转到opendrive.com网站. ...

  2. 【概率DP入门】

    http://www.cnblogs.com/kuangbin/archive/2012/10/02/2710606.html 有关概率和期望问题的研究 摘要 在各类信息学竞赛中(尤其是ACM竞赛中) ...

  3. 前端开发必备的Sublime 3插件

    Sublime的大名已经无需我介绍了,首先先介绍如何启用插件安装功能: 打开Sublime 3,然后按 ctrl+` 或者在View → Show Console 在打开的窗口里黏贴这个网站上的代码( ...

  4. 《think in python》学习-10

    think in python 10 列表 和字符串相似,列表是值得序列.在列表中,它可以是任何类型,列表中的值成为元素,有时也称为列表项 s = [10,20,30,40] print s #列表也 ...

  5. UVA 1660 Cable TV Network

    题意: 求一个无向图的点连通度. 分析: 把一个点拆成一个入点和一个出点,之间连一条容量为1的有向边,表示能被用一次.最大流求最小割即可.套模板就好 代码; #include <iostream ...

  6. radio与checkbox

    最近一直在学习Javascript与asp.net MVC4,每天都在跟着书学习.这样总感觉自己看的很抽象,没有点实际的意义.而且,每次看的东西很容易忘记,所以打算在这里记录自己的学习笔记. Java ...

  7. IIS Could not load file or assembly 'CLDBCommon.DLL' or one of its dependencies.找不到指定的模块

    1.卸载原来的.NET4.0,从新下载.NET4.5.1完整安装程序.后问题解决附:.NET4.5.1下载地址:https://www.microsoft.com/zh-cn/download/det ...

  8. C++学习之重载运算符1

    C++除可重载函数之后,还允许定义已有的运算符,这样通过运算符重载可像处理数据使用它们. 先来个代码 #include<iostream> using namespace std; cla ...

  9. 在windows平台下忘记了root的密码如何解决?

    1.打开MySQL配置文件 my.ini中,添加上skip-grant-tables,可以添加到文件的末尾或者是这添加到[mysqld]的下面. 2.然后重启MYSQL服务 windows环境中: n ...

  10. mysql学习(五)-字段属性

    字段属性: unsigned: 无符号类型,只能修饰数值类型: create table if not exists t1(id int unsigned); zerofill:前端填0 //只能修饰 ...