【声明】

欢迎转载,但请保留文章原始出处→_→

生命壹号:http://www.cnblogs.com/smyhvae/

文章来源:http://www.cnblogs.com/smyhvae/p/4000483.html

【正文】

一、ListFragement的介绍:

ListFragment继承于Fragment。因此它具有Fragment的特性,能够作为activity中的一部分,目的也是为了使页面设计更加灵活。相比Fragment,ListFragment的内容是以列表(list)的形式显示的。

1、ListFragment布局:

ListFragment的默认布局包含一个list view。因此,在ListFragment对应的布局文件中,必须指定一个 android:id 为 “@android:id/list” 的ListView控件! 若用户想修改listview,可以在onCreateView(LayoutInflater, ViewGroup, Bundle)中进行修改。当然,用户也可以在ListFragment的布局中包含其它的控件。

下面是官方文档中ListFragment对应的一个layout示例:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="8dp"
android:paddingRight="8dp"> <ListView android:id="@id/android:list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00FF00"
android:layout_weight="1"
android:drawSelectorOnTop="false"/> <TextView android:id="@id/android:empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF0000"
android:text="No data"/>
</LinearLayout>

ListView中每一行的显示内容,是通过设置适配器ListAdapter来实现的。我们既可以自定义,也可以采用系统默认的layout。后面的应用实例中,会分别列举2种情况下的显示

2、绑定数据:

ListFragment绑定ListView的数据(即绑定适配器)时,必须通过ListFragment.setListAdapter()接口来绑定数据,而不是使用ListView.setAdapter() 或其它方法

二、通过ArrayAdapter来加载ListFragment的举例:

【举例】现在将平板电脑分成三部分:点击左侧的按钮,出现中间的新闻标题列表(ListFragment),点击中间ListFragment的某个item,在最右侧的fragment中显示详情。

新建工程文件m01_ListFragment01:

(1)定义activity_main.xml的布局

activity_main.xml的代码如下:

<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" > <LinearLayout
android:id="@+id/left"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#cccccc"
android:orientation="horizontal" > <Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="14sp"
android:text="show ListFragment" />
</LinearLayout> <LinearLayout
android:id="@+id/center"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:background="#AFEEEE"
android:orientation="vertical" >
</LinearLayout> <LinearLayout
android:id="@+id/center"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:background="#00FFFF"
android:orientation="vertical" >
</LinearLayout> </LinearLayout>

实际上分配了三个线性布局,左侧显示按钮,中间显示标题,右侧显示详情。这个布局文件对应的可视化界面如下:

(2)定义中间的ListFragment,即新建文件ArticleListFragment.java:

ArticleListFragment.java的代码如下:

 package com.example.m01_listfragment01;

 import java.util.ArrayList;
import java.util.List; import android.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter; public class ArticleListFragment extends ListFragment { private ArrayAdapter<String> adapter; @Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState); //定义一个数组
List<String> data = new ArrayList<String>();
for (int i = 0; i < 30; i++) {
data.add("smyh" + i);
}
//将数组加到ArrayAdapter当中
adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, data);
//绑定适配器时,必须通过ListFragment.setListAdapter()接口,而不是ListView.setAdapter()或其它方法
setListAdapter(adapter);
} @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return super.onCreateView(inflater, container, savedInstanceState);
} @Override
public void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
}

核心代码是22至32行:我们让这个Fragment继承ListFragment,然后在onCreate()方法中定义一个ArrayAdapter,将数据放进去,最后绑定适配器就行了。需要注意的是,由于我们继承的是ListFragment,这个Fragment默认自带了一个布局,所以我们不需要重新新建布局文件了。

(3)将中间的ListFragment加载到Activity当中去。当我们点击按钮时,就开始加载这个Fragment:

MainActivity.java的代码如下:

 package com.example.m01_listfragment01;

 import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button; public class MainActivity extends Activity { private FragmentManager manager;
private FragmentTransaction transaction;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() { //点击按钮,加载ListFragment
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
manager = getFragmentManager();
transaction = manager.beginTransaction();
ArticleListFragment articleListFragment = new ArticleListFragment();
transaction.add(R.id.center, articleListFragment, "article");
transaction.commit();
}
}); } @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

这个代码比较简单,就不多解释了。

现在运行程序,初始界面如下:

点击左侧的按钮后,显示如下:

注:如果想实现:点击中间的某个item,弹出吐司显示那个item中的内容,可以在上方的ArticleListFragment.java中的监听事件里添加如下代码:

(代码放置的位置是:让它和Fragment的生命周期方法并列就行了)

     @Override
public void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String item = adapter.getItem(position);
Toast.makeText(getActivity(), item, 1).show();

由此我们可以看到,监听事件的函数为onListItemClick(),可以直接写,不需要set。

这里面关键代码在第05行,通过getItem()接收那个item,然后用字符串来接收。

我们先去掉这部分的监听事件代码,继续往下看。

(4)点击中间ListFragment的item,加载右边的DetailFragment:

我们在中间ListFragment中添加一个按钮的监听事件,监听事件的函数为onListItemClick(),ArticleListFragment.java在上面代码的基础之上,添加的代码如下:

(代码放置的位置是:让它和Fragment的生命周期方法并列就行了)

     //点击按钮,加载最右侧的Fragment
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id); //点击按钮后,加载右边的Fragment
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
DetailFragment detailFragment = new DetailFragment();
//记住:这个地方必须用replace,而不是用add
transaction.replace(R.id.right, detailFragment, "detailFragment");

//将中间的item的内容放到Bundle对象当中,然后放到最右侧Frament的参数当中
String item = adapter.getItem(position);
Bundle args = new Bundle();
args.putString("item",item);
detailFragment.setArguments(args);
//
Toast.makeText(getActivity(), item, 1).show(); transaction.commit();
}

上面的代码中,我们是在中间的Fragment中点击按钮,然后加载右边的Fragment,然后要注意14至18行的核心代码,看一下它是如何通过bundle来传递数据的。

需要注意的是,第12行代码必须用replace的方式加载右侧的fragment,而不是add;如果用add,运行的错误稍后将展示出来。

(5)定义右边的DetailFragment:

先定义布局文件,在里面加一个TextView,fragment_detail.xml的代码如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" > <TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>

然后新建文件,DetailFragment.java的代码如下:

 package com.example.m01_listfragment01;

 import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView; public class DetailFragment extends Fragment { @Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
} @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.fragment_detail, null);
TextView textView = (TextView)view.findViewById(R.id.textView1);
textView.setText(""+getArguments().getString("item"));
return view;
} @Override
public void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
}

核心代码是第25行,仔细看一下我们是怎么通过键值对来拿到中间的Fragment传递过来的item的内容。

现在运行程序,一次点击左边的按钮和中间的item,效果如下:

如果我们在中间的Fragment中错误地通过add方式加载右边的Fragment,而不是通过replace方式,最终错误的效果如下:

也就是说,每点击一次中间的item,就会在右边继续加载一个文本,而不是替代的方式,很显然,这种方式不是我们想要的。

【索引】

如果你对本文存在疑惑,请参考本人关于Fragment的系列文章:(不断更新)

Android系列之Fragment(一)----Fragment加载到Activity当中

Android系列之Fragment(二)----Fragment的生命周期和返回栈

Android系列之Fragment(三)----Fragment和Activity之间的通信(含接口回调)

Android系列之Fragment(四)----ListFragment的使用

Android系列之Fragment(四)----ListFragment的使用的更多相关文章

  1. Android系列之Fragment(三)----Fragment和Activity之间的通信(含接口回调)

    ​[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/ ...

  2. Android系列之Fragment(二)----Fragment的生命周期和返回栈

    ​[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/ ...

  3. Android系列之Fragment(一)----Fragment加载到Activity当中

    Android上 的界面展示都是通过Activity实现的,Activity实在是太常用了.但是Activity也有它的局限性,同样的界面在手机上显示可能很好看, 在平板上就未必了,因为平板的屏幕非常 ...

  4. Android Studio 单刷《第一行代码》系列 06 —— Fragment 生命周期

    前情提要(Previously) 本系列将使用 Android Studio 将<第一行代码>(书中讲解案例使用Eclipse)刷一遍,旨在为想入坑 Android 开发,并选择 Andr ...

  5. Android Studio 单刷《第一行代码》系列 05 —— Fragment 基础

    前情提要(Previously) 本系列将使用 Android Studio 将<第一行代码>(书中讲解案例使用Eclipse)刷一遍,旨在为想入坑 Android 开发,并选择 Andr ...

  6. 【转】 Pro Android学习笔记(四三):Fragment(8):再谈Transaction和管理器

    目录(?)[-] Transaction的一些操作 再谈FragmentManager 调用其他fragment的方法 唤起activity 唤起fragment和相互通信 一些其它 Transact ...

  7. 【转】 Pro Android学习笔记(四十):Fragment(5):适应不同屏幕或排版

    目录(?)[-] 设置横排和竖排的不同排版风格 改写代码 对于fragment,经常涉及不同屏幕尺寸和不同的排版风格.我们在基础小例子上做一下改动,在横排的时候,仍是现实左右两个fragment,在竖 ...

  8. 【转】 Pro Android学习笔记(四二):Fragment(7):切换效果

    目录(?)[-] 利用setTransition 利用setCustomAnimations 通过ObjectAnimator自定义动态效果 程序代码的编写 利用fragment transactio ...

  9. ZT android -- 蓝牙 bluetooth (四)OPP文件传输

    android -- 蓝牙 bluetooth (四)OPP文件传输 分类: Android的原生应用分析 2013-06-22 21:51 2599人阅读 评论(19) 收藏 举报 4.2源码AND ...

随机推荐

  1. Eclipse下Android开发的问题:Installation error: INSTALL_FAILED_NO_MATCHING_ABIS 解决办法

    在Android模拟器上安装apk的时候出现   INSTALL_FAILED_NO_MATCHING_ABIS 这个错误提示的解决办法. 是由于使用了native libraries .该nativ ...

  2. Vue列表渲染

    gitHub地址:https://github.com/lily1010/vue_learn/tree/master/lesson09 一 for循环数组 <!DOCTYPE html> ...

  3. javascript --- 子对象访问父对象的方式

    在传统面向对象的编程语言里,都会提供一种子类访问父类的特殊语法,引文我们在实现子类方法往往需要父类方法的额外辅助.在这种情况下,子类通常会调用父类中的同名方法,最终以便完成工作. javascript ...

  4. RHEL7用户管理

    本文介绍Linux的用户管理 用户管理 Linux 是一个可以实现多用户登陆的操作系统,不同用户可以同时登陆同一台主机,他们共享一些主机的资源,但他们也分别有自己的用户空间,用于存放各自的文件. 但实 ...

  5. Flexbox实现垂直水平居中

    Flexbox(伸缩盒)是CSS3中新增的特性,利用这个属性可以解决页面中的居中问题.只需要3行代码就可以实现,不需要设置元素的尺寸,能够自适应页面. 这个方法只能在现代浏览器上有效,IE10+.ch ...

  6. C#加密算法总结

    C#加密算法总结 MD5加密 /// <summary> /// MD5加密 /// </summary> /// <param name="strPwd&qu ...

  7. GetStartedWithWin10Develop

    GetStartedWithWin10Develop 首先要确保已经配置好win10开发环境,开始第一个win10开发的HelloWorld 1.首先创建你的win10项目(示例的项目名称为 Hell ...

  8. 配置windows失败,还原更新,请勿关机

    同事叫我帮忙弄一下电脑,开机,出现"配置Windows Update失败,还原更改,请勿关闭计算机",我从来不更新Windows Update,更新都为成功,第一次遇到失败了,不知 ...

  9. Atitit.json xml 序列化循环引用解决方案json

    Atitit.json xml 序列化循环引用解决方案json 1. 循环引用1 2. 序列化循环引用解决方法1 2.1. 自定义序列化器1 2.2. 排除策略1 2.3. 设置序列化层次,一般3级别 ...

  10. android lsitview setOnItemLongClickListener 无效或不执行

    今天遇到了lsitview的setOnItemLongClickListener的方法不执行,我是在listview中的每一个ITEM都存放了不同的布局:给整个item布局设置了点击事件onClick ...