android listview进阶实例分享

上一篇android listview初步学习实例代码分享了一个listview初级实例,本文我们看看一个进阶实例。

目录结构:

MainActivity2

package com.example1.listviewpracticvce;
/*
 * 本activity实现的功能:
 * 将数据库中的数据用listview显示出来
 */
import com.example1.listviewdao.PersonDAO;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.SimpleCursorAdapter.ViewBinder;
public class MainActivity2 extends Activity {
	ListView lvPerson;
	@Override
	    protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.person);
		PersonDAO personDAO = new PersonDAO(this);
		Cursor cursor = personDAO.getPersons();
		//cursor类似一个指针
		lvPerson = (ListView) findViewById(R.id.lvPerson);
		//SimpleCursorAdapter(context, layout,   c,   from,    to    )
		//            listview的布局    cursor 需要显示的列  在哪个控件中显示
		//数组开头的列必须是"_id"
		SimpleCursorAdapter adapter = new PersonAdapter(this, R.layout.person_item, cursor,
		          new String[]{ "_id", "pname", "pgender" },
		          new int[]{ R.id.tvPid, R.id.tvPname, R.id.ivPgender });
		//     SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.person_item, cursor,
		//     new String[]{ "_id", "pname", "pgender" }, //要显示的列
		//     new int[]{ R.id.tvPid, R.id.tvPname, R.id.ivPgender });//显示每行所用控件
		//为了将性别显示为图片,这里复写了SimpleCursorAdapter这个类
		lvPerson.setAdapter(adapter);
		lvPerson.setOnItemClickListener(new OnItemClickListener()
		      {
			@Override
			        public void onItemClick(AdapterView<?> parent, View view, int position, long id)
			        {
				Cursor cursor = (Cursor) parent.getItemAtPosition(position);
				Toast.makeText(getApplicationContext(), cursor.getString(1), Toast.LENGTH_sHORT).show();
			}
		}
		);
	}
}
//利用源代码定制
class PersonAdapter extends SimpleCursorAdapter
  {
	private Cursor mCursor;
	protected int[] mFrom;
	protected int[] mTo;
	private ViewBinder mViewBinder;
	public PersonAdapter(Context context, int layout, Cursor c, String[] from, int[] to)
	    {
		super(context, layout, c, from, to);
		mCursor = c;
		mTo = to;
		findColumns(from);
	}
	@Override
	    public void bindView(View view, Context context, Cursor cursor)
	    {
		final ViewBinder binder = mViewBinder;
		final int count = mTo.length;
		final int[] from = mFrom;
		final int[] to = mTo;
		for (int i = 0; i < count; i++)
		      {
			final View v = view.findViewById(to[i]);
			if (v != null)
			        {
				Boolean bound = false;
				if (binder != null)
				          {
					bound = binder.setViewValue(v, cursor, from[i]);
				}
				if (!bound)
				          {
					String text = cursor.getString(from[i]);
					if (text == null)
					            {
						text = "";
					}
					if (v instanceof TextView)
					            {
						setViewText((TextView) v, text);
					} else if (v instanceof ImageView)
					            {
						if (text.equals("男"))
						              {
							setViewImage((ImageView) v, String.valueOf(R.drawable.boy));
						} else
						              {
							setViewImage((ImageView) v, String.valueOf(R.drawable.girl));
						}
					} else
					            {
						throw new IllegalStateException(v.getClass().getName() + " is not a " + " view that can be bounds by this SimpleCursorAdapter");
					}
				}
			}
		}
	}
	private void findColumns(String[] from)
	    {
		if (mCursor != null)
		      {
			int i;
			int count = from.length;
			if (mFrom == null || mFrom.length != count)
			        {
				mFrom = new int[count];
			}
			for (i = 0; i < count; i++)
			        {
				mFrom[i] = mCursor.getColumnIndexOrThrow(from[i]);
			}
		} else
		      {
			mFrom = null;
		}
	}
}

DBOpenHelper

package com.example1.listviewdao;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBOpenHelper extends SQLiteOpenHelper
{
	private static final int VERSION = 1;
	private static final String DBNAME = "data.db";
	private static final String PERSON="t_person";
	public DBOpenHelper(Context context)
	  {
		super(context, DBNAME, null, VERSION);
	}
	@Override
	  public void onCreate(SQLiteDatabase db)
	  {
		db.execSQL("create table "+PERSON+" (_id varchar(4) primary key,pname varchar(20),pgender varchar(2))");
		db.execSQL("insert into t_person (_id, pname, pgender) values ('1001','张三','男')");
		db.execSQL("insert into t_person (_id, pname, pgender) values ('1002','李四','男')");
		db.execSQL("insert into t_person (_id, pname, pgender) values ('1003','王五','女')");
		db.execSQL("insert into t_person (_id, pname, pgender) values ('1004','赵钱','男')");
		db.execSQL("insert into t_person (_id, pname, pgender) values ('1005','孙李','女')");
		db.execSQL("insert into t_person (_id, pname, pgender) values ('1006','周吴','男')");
		db.execSQL("insert into t_person (_id, pname, pgender) values ('1007','郑王','男')");
		db.execSQL("insert into t_person (_id, pname, pgender) values ('1008','冯陈','男')");
		db.execSQL("insert into t_person (_id, pname, pgender) values ('1009','褚卫','女')");
		db.execSQL("insert into t_person (_id, pname, pgender) values ('1010','蒋沈','男')");
		db.execSQL("insert into t_person (_id, pname, pgender) values ('1011','韩杨','男')");
		db.execSQL("insert into t_person (_id, pname, pgender) values ('1012','朱秦','男')");
		db.execSQL("insert into t_person (_id, pname, pgender) values ('1013','尤许','男')");
	}
	@Override
	  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
	  {
	}
}

Person

package com.example1.listviewdao;
public class Person
{
	private String pid;
	private String pname;
	private String pgender;
	public Person()
	  {
		super();
	}
	public Person(String pid, String pname, String pgender)
	  {
		super();
		this.pid = pid;
		this.pname = pname;
		this.pgender = pgender;
	}
	public String getPid()
	  {
		return pid;
	}
	public void setPid(String pid)
	  {
		this.pid = pid;
	}
	public String getPname()
	  {
		return pname;
	}
	public void setPname(String pname)
	  {
		this.pname = pname;
	}
	public String getPgender()
	  {
		return pgender;
	}
	public void setPgender(String pgender)
	  {
		this.pgender = pgender;
	}
	@Override
	  public String toString()
	  {
		return "pid=" + pid + ";pname=" + pname + ";pgender=" + pgender;
	}
}

PersonDAO

package com.example1.listviewdao;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class PersonDAO
{
	private DBOpenHelper helper;
	private SQLiteDatabase db;
	public PersonDAO(Context context)
	  {
		helper = new DBOpenHelper(context);
	}
	public Cursor getPersons(int start, int count)
	  {
		db = helper.getWritableDatabase();
		Cursor cursor=db.query("t_person", new String[]{"_id","pname","pgender"}, null, null, null, null, "_id desc",start+","+count);
		return cursor;
	}
	public Cursor getPersons()
	  {
		db = helper.getWritableDatabase();
		Cursor cursor=db.query("t_person", new String[]{"_id,pname,pgender"}, null, null, null, null, null);
		return cursor;
	}
	public long getCount()
	  {
		db = helper.getWritableDatabase();
		Cursor cursor = db.rawQuery("select count(_id) from t_person", null);
		if (cursor.moveToNext())
		    {
			return cursor.getlong(0);
		}
		return 0;
	}
}

person_item.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="horizontal"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <TextView
    android:id="@+id/tvPid"
    android:layout_width="70dp"
    android:layout_height="50dp"
    android:gravity="center"
    android:textSize="15sp"
    />
  <TextView
    android:id="@+id/tvPname"
    android:layout_width="190dp"
    android:layout_height="50dp"
    android:gravity="center"
    android:textSize="15sp"
    /> 

  <ImageView
    android:id="@+id/ivPgender"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    /> 

   <!--
  <TextView
    android:id="@+id/ivPgender"
    android:layout_width="wrap_content"
    android:layout_height="50dp"
    android:gravity="center"
    android:textSize="15sp"
    />
    -->
</LinearLayout> 

person.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <LinearLayout
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    >
    <TextView
      android:layout_width="70dp"
      android:layout_height="wrap_content"
      android:gravity="center"
      android:text="编号"
      android:textSize="20sp"
      android:textStyle="bold"
      />
    <TextView
      android:layout_width="190dp"
      android:layout_height="wrap_content"
      android:gravity="center"
      android:text="姓名"
      android:textSize="20sp"
      android:textStyle="bold"
      />
    <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="性别"
      android:textSize="20sp"
      android:textStyle="bold"
      />
  </LinearLayout>
  <ListView
    android:id="@+id/lvPerson"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/bg"
    android:scrollingCache="false"
    android:divider="@drawable/line"
    />
</LinearLayout> 

结果展示

总结

以上就是本文关于android listview进阶实例分享的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

(0)

相关推荐

  • android listview初步学习实例代码

    在android开发中ListView是比较常用的组件,下面分享一个实例. MainActivity package com.example1.listviewpracticvce; /* * 本例子实现的功能: * 用listview显示给定的一个静态数组,数组定义在string.xml中攻或者activity中 */ import android.net.sip.SipAudioCall.Listener; import android.os.Bundle; import android.a

  • Android开发listview选中高亮简单实现代码分享

    百度了好几种listview选中高亮的办法都太繁琐太不友好,我在无意中发现了一种简单有效的办法,而且代码量极少 源码如下: MainActivity.java package com.listviewtest; import android.os.Bundle; import android.app.Activity; import android.graphics.drawable.Drawable; import android.view.View; import android.widge

  • Android ListView实现下拉顶部图片变大效果

    本文实例为大家分享了Android ListView下拉顶部图片变大的具体代码,供大家参考,具体内容如下 在git上查看牛人的代码,发现是反编译别人的代码,还没加注释,代码也没有完全编译完整,所以这里我做的简单的注释,仅供学习. 变量说明 这里变量包含了:自定义返回动画加速度.自定义动画线程.头部图片view,最后的y坐标,做好的比例,做大的比例等. private static final String TAG = "PullToZoomListView"; private stat

  • android使用PullToRefresh框架实现ListView下拉刷新上拉加载更多

    本文实例为大家分享了Android实现ListView下拉刷新上拉加载更多的具体代码,供大家参考,具体内容如下 其实谷歌官方目前已经推出ListView下拉刷新框架SwipeRefreshLayout,想了解的朋友可以点击 android使用SwipeRefreshLayout实现ListView下拉刷新上拉加载了解一下: 大家不难发现当你使用SwipeRefreshLayout下拉的时候布局文件不会跟着手势往下滑,而且想要更改这个缺陷好像非常不容易. 虽然SwipeRefreshLayout非

  • Android开发实现仿QQ消息SwipeMenuListView滑动删除置顶功能【附源码下载】

    本文实例讲述了Android开发实现仿QQ消息SwipeMenuListView滑动删除置顶功能.分享给大家供大家参考,具体如下: 一.先来效果图 二.实现步骤: 1. 在项目build.gradle里面添加包 compile 'com.baoyz.swipemenulistview:library:1.3.0' 2. xml布局文件 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

  • Android ListView与RecycleView的对比使用解析

    ListView,就如其名,是用来显示列表的一种View,而RecycleView,是其的加强版,今天带来的是这两个几乎具有相同的功能的对比使用 先从ListView说起吧 ListView: 1.在布局文件中使用ListView,并为其定义一个id,方便我们之后的调用,宽高与父控件相同 2.准备数据,将数据添加到ArrayAdapter适配器当中 3.在Activity的java文件中使用findviewbyid找到ListView实例,为其设置Adapter 4.实现ListView的ite

  • android使用SwipeRefreshLayout实现ListView下拉刷新上拉加载

    本文实例为大家分享了android实现ListView下拉刷新上拉加载的具体代码,供大家参考,具体内容如下 这次使用的是系统的SwipeRefreshLayout实现下拉刷新,和设置ListView的滑动监听判断是否滑动到最底部然后加载更多: 这个要比PullToRefreshListView简单很多,想PullToRefreshListView实现下拉刷新上拉加载的可以看这篇博客: android使用PullToRefresh框架实现ListView下拉刷新上拉加载更多 至于使用哪一种大家可以

  • android listview进阶实例分享

    上一篇<android listview初步学习实例代码>分享了一个listview初级实例,本文我们看看一个进阶实例. 目录结构: MainActivity2 package com.example1.listviewpracticvce; /* * 本activity实现的功能: * 将数据库中的数据用listview显示出来 */ import com.example1.listviewdao.PersonDAO; import android.app.Activity; import

  • Android中ListView用法实例分析

    本文实例分析了Android中ListView用法.分享给大家供大家参考,具体如下: 通过在Layout中添加ListView Widget可以达到在页面布局具有列表效果的交互页面.在这里通过举例来说明怎样在Layout中添加ListView以及怎样应用. 配合设计了两个事件Listener:  OnItemSelectedListener事件为鼠标的滚轮转动时所选择的值:OnItemClickListener事件则为当鼠标单击时,所触发的事件.由此可以区别出list中的"选择"与&q

  • Android控件之ListView用法实例详解

    本文实例讲述了Android控件之ListView用法.分享给大家供大家参考.具体如下: 示例一: 在android开发中ListView是比较常用的组件,它以列表的形式展示具体内容,并且能够根据数据的长度自适应显示. main.xml布局文件: <?xml version="1.0" encoding="utf-8"?> <LinearLayout android:id="@+id/LinearLayout01" androi

  • Android ListView实现仿iPhone实现左滑删除按钮的简单实例

    需要自定义ListView.这里就交FloatDelListView吧. 复写onTouchEvent方法.如下: @Override public boolean onTouchEvent(MotionEvent ev) { switch (ev.getAction()) { case MotionEvent.ACTION_DOWN:<BR> // 获取按下的条目视图(child view) int childCount = getChildCount(); int[] listViewCo

  • Android ListView自动生成列表条目的实例

    activity_list.xml文件代码如下: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent

  • Android listview与adapter详解及实例代码

    一个ListView通常有两个职责. (1)将数据填充到布局. (2)处理用户的选择点击等操作. 第一点很好理解,ListView就是实现这个功能的.第二点也不难做到,在后面的学习中读者会发现,这非常简单. 一个ListView的创建需要3个元素. (1)ListView中的每一列的View. (2)填入View的数据或者图片等. (3)连接数据与ListView的适配器. 也就是说,要使用ListView,首先要了解什么是适配器.适配器是一个连接数据和AdapterView(ListView就

  • Android ListView中动态添加RaidoButton的实例详解

    Android ListView中动态添加RaidoButton的实例详解 这里讲解的内容是:从数据库中取得数据,将这些数据的value值赋值给Radiobutton的text属性,将这些数据的key值赋值给radiobutton的key值.同时实现点击一整行,更换radiobutton选择. XML代码:主要是添加一个ListView控件 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android&q

  • Android 中ScrollView嵌套GridView,ListView的实例

    Android 中ScrollView嵌套GridView,ListView的实例 在Android开发中,经常有一些UI需要进行固定style的动态布局,然而由于现在的UI都喜欢把一个界面拉的很长,所以我们很多情况下需要使用ScrollView来嵌套列表控件来实现UI.这样就导致了很多不顺心的问题. 问题一:列表控件显示不完全 原因是嵌套情况下,ScrollView不能正确的计算列表控件的高度. 有两种解决方案 方案一 在适配器赋值完成后代码动态计算列表的高度.这里贴出ListView的计算代

  • Android ListView万能适配器实例代码

    ListView是开发中最常用的控件了,但是总是会写重复的代码,浪费时间又没有意义. 最近参考一些资料,发现一个万能ListView适配器,代码量少,节省时间,总结一下分享给大家. 首先有一个自定义的Adapter继承于BaseAdapter,下面是自定义的Adapter,精华在getView()方法中 package com.example.mylistview.util; import java.util.List; import android.content.Context; impor

  • Android listview ExpandableListView实现多选,单选,全选,edittext实现批量输入的实例代码

    最近在项目开发中,由于项目的需求要实现一些列表的单选,多选,全选,批量输入之类的功能,其实功能的实现倒不是很复杂,需求中也没有涉及到复杂的动画什么之类,主要是解决列表数据复用的问题,解决好这个就可以了.下面是最近项目中涉及到的一些: listview实现多选.全选.取消全选: 下面是适配器,一开始在适配器的构造函数中,对数据进行初始化,同时定义一个集合用于管理listview的点击: class BatchAdpter extends BaseAdapter { private HashMap<

随机推荐