Android列表实现(3)_自定义列表适配器思路及实现代码

下面的例子为使用自定义的列表适配器来显示列表。


代码如下:

View Code
import android.os.Bundle;
import android.app.ListActivity;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends ListActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new SpeechListAdapter(this));
}
/**
* A sample ListAdapter that presents content from arrays of speeches and
* text.
*
*/
private class SpeechListAdapter extends BaseAdapter {
public SpeechListAdapter(Context context) {
mContext = context;
}
/**
* The number of items in the list is determined by the number of speeches
* in our array.
*
* @see android.widget.ListAdapter#getCount()
*/
public int getCount() {
return mTitles.length;
}
/**
* Since the data comes from an array, just returning the index is
* sufficent to get at the data. If we were using a more complex data
* structure, we would return whatever object represents one row in the
* list.
*
* @see android.widget.ListAdapter#getItem(int)
*/
public Object getItem(int position) {
return position;
}
/**
* Use the array index as a unique id.
*
* @see android.widget.ListAdapter#getItemId(int)
*/
public long getItemId(int position) {
return position;
}
/**
* Make a SpeechView to hold each row.
*
* @see android.widget.ListAdapter#getView(int, android.view.View,
* android.view.ViewGroup)
*/
public View getView(int position, View convertView, ViewGroup parent) {
SpeechView sv;
if (convertView == null) {
sv = new SpeechView(mContext, mTitles[position],
mDialogue[position]);
} else {
sv = (SpeechView) convertView;
sv.setTitle(mTitles[position]);
sv.setDialogue(mDialogue[position]);
}
return sv;
}
/**
* Remember our context so we can use it when constructing views.
*/
private Context mContext;
/**
* Our data, part 1.
*/
private String[] mTitles =
{
"Henry IV (1)",
"Henry V",
"Henry VIII",
"Richard II",
"Richard III",
"Merchant of Venice",
"Othello",
"King Lear"
};
/**
* Our data, part 2.
*/
private String[] mDialogue =
{
"So shaken as we are, so wan with care," +
"Find we a time for frighted peace to pant," +
"And breathe short-winded accents of new broils" +
"To be commenced in strands afar remote." +
"No more the thirsty entrance of this soil" +
"Shall daub her lips with her own children's blood;" +
"Nor more shall trenching war channel her fields," +
"Nor bruise her flowerets with the armed hoofs" +
"Of hostile paces: those opposed eyes," +
"Which, like the meteors of a troubled heaven," +
"All of one nature, of one substance bred," +
"Did lately meet in the intestine shock" +
"And furious close of civil butchery" +
"Shall now, in mutual well-beseeming ranks," +
"March all one way and be no more opposed" +
"Against acquaintance, kindred and allies:" +
"The edge of war, like an ill-sheathed knife," +
"No more shall cut his master. Therefore, friends," +
"As far as to the sepulchre of Christ," +
"Whose soldier now, under whose blessed cross" +
"We are impressed and engaged to fight," +
"Forthwith a power of English shall we levy;" +
"Whose arms were moulded in their mothers' womb" +
"To chase these pagans in those holy fields" +
"Over whose acres walk'd those blessed feet" +
"Which fourteen hundred years ago were nail'd" +
"For our advantage on the bitter cross." +
"But this our purpose now is twelve month old," +
"And bootless 'tis to tell you we will go:" +
"Therefore we meet not now. Then let me hear" +
"Of you, my gentle cousin Westmoreland," +
"What yesternight our council did decree" +
"In forwarding this dear expedience.",
"Hear him but reason in divinity," +
"And all-admiring with an inward wish" +
"You would desire the king were made a prelate:" +
"Hear him debate of commonwealth affairs," +
"You would say it hath been all in all his study:" +
"List his discourse of war, and you shall hear" +
"A fearful battle render'd you in music:" +
"Turn him to any cause of policy," +
"The Gordian knot of it he will unloose," +
"Familiar as his garter: that, when he speaks," +
"The air, a charter'd libertine, is still," +
"And the mute wonder lurketh in men's ears," +
"To steal his sweet and honey'd sentences;" +
"So that the art and practic part of life" +
"Must be the mistress to this theoric:" +
"Which is a wonder how his grace should glean it," +
"Since his addiction was to courses vain," +
"His companies unletter'd, rude and shallow," +
"His hours fill'd up with riots, banquets, sports," +
"And never noted in him any study," +
"Any retirement, any sequestration" +
"From open haunts and popularity.",
"I come no more to make you laugh: things now," +
"That bear a weighty and a serious brow," +
"Sad, high, and working, full of state and woe," +
"Such noble scenes as draw the eye to flow," +
"We now present. Those that can pity, here" +
"May, if they think it well, let fall a tear;" +
"The subject will deserve it. Such as give" +
"Their money out of hope they may believe," +
"May here find truth too. Those that come to see" +
"Only a show or two, and so agree" +
"The play may pass, if they be still and willing," +
"I'll undertake may see away their shilling" +
"Richly in two short hours. Only they" +
"That come to hear a merry bawdy play," +
"A noise of targets, or to see a fellow" +
"In a long motley coat guarded with yellow," +
"Will be deceived; for, gentle hearers, know," +
"To rank our chosen truth with such a show" +
"As fool and fight is, beside forfeiting" +
"Our own brains, and the opinion that we bring," +
"To make that only true we now intend," +
"Will leave us never an understanding friend." +
"Therefore, for goodness' sake, and as you are known" +
"The first and happiest hearers of the town," +
"Be sad, as we would make ye: think ye see" +
"The very persons of our noble story" +
"As they were living; think you see them great," +
"And follow'd with the general throng and sweat" +
"Of thousand friends; then in a moment, see" +
"How soon this mightiness meets misery:" +
"And, if you can be merry then, I'll say" +
"A man may weep upon his wedding-day.",
"First, heaven be the record to my speech!" +
"In the devotion of a subject's love," +
"Tendering the precious safety of my prince," +
"And free from other misbegotten hate," +
"Come I appellant to this princely presence." +
"Now, Thomas Mowbray, do I turn to thee," +
"And mark my greeting well; for what I speak" +
"My body shall make good upon this earth," +
"Or my divine soul answer it in heaven." +
"Thou art a traitor and a miscreant," +
"Too good to be so and too bad to live," +
"Since the more fair and crystal is the sky," +
"The uglier seem the clouds that in it fly." +
"Once more, the more to aggravate the note," +
"With a foul traitor's name stuff I thy throat;" +
"And wish, so please my sovereign, ere I move," +
"What my tongue speaks my right drawn sword may prove.",
"Now is the winter of our discontent" +
"Made glorious summer by this sun of York;" +
"And all the clouds that lour'd upon our house" +
"In the deep bosom of the ocean buried." +
"Now are our brows bound with victorious wreaths;" +
"Our bruised arms hung up for monuments;" +
"Our stern alarums changed to merry meetings," +
"Our dreadful marches to delightful measures." +
"Grim-visaged war hath smooth'd his wrinkled front;" +
"And now, instead of mounting barded steeds" +
"To fright the souls of fearful adversaries," +
"He capers nimbly in a lady's chamber" +
"To the lascivious pleasing of a lute." +
"But I, that am not shaped for sportive tricks," +
"Nor made to court an amorous looking-glass;" +
"I, that am rudely stamp'd, and want love's majesty" +
"To strut before a wanton ambling nymph;" +
"I, that am curtail'd of this fair proportion," +
"Cheated of feature by dissembling nature," +
"Deformed, unfinish'd, sent before my time" +
"Into this breathing world, scarce half made up," +
"And that so lamely and unfashionable" +
"That dogs bark at me as I halt by them;" +
"Why, I, in this weak piping time of peace," +
"Have no delight to pass away the time," +
"Unless to spy my shadow in the sun" +
"And descant on mine own deformity:" +
"And therefore, since I cannot prove a lover," +
"To entertain these fair well-spoken days," +
"I am determined to prove a villain" +
"And hate the idle pleasures of these days." +
"Plots have I laid, inductions dangerous," +
"By drunken prophecies, libels and dreams," +
"To set my brother Clarence and the king" +
"In deadly hate the one against the other:" +
"And if King Edward be as true and just" +
"As I am subtle, false and treacherous," +
"This day should Clarence closely be mew'd up," +
"About a prophecy, which says that 'G'" +
"Of Edward's heirs the murderer shall be." +
"Dive, thoughts, down to my soul: here" +
"Clarence comes.",
"To bait fish withal: if it will feed nothing else," +
"it will feed my revenge. He hath disgraced me, and" +
"hindered me half a million; laughed at my losses," +
"mocked at my gains, scorned my nation, thwarted my" +
"bargains, cooled my friends, heated mine" +
"enemies; and what's his reason? I am a Jew. Hath" +
"not a Jew eyes? hath not a Jew hands, organs," +
"dimensions, senses, affections, passions? fed with" +
"the same food, hurt with the same weapons, subject" +
"to the same diseases, healed by the same means," +
"warmed and cooled by the same winter and summer, as" +
"a Christian is? If you prick us, do we not bleed?" +
"if you tickle us, do we not laugh? if you poison" +
"us, do we not die? and if you wrong us, shall we not" +
"revenge? If we are like you in the rest, we will" +
"resemble you in that. If a Jew wrong a Christian," +
"what is his humility? Revenge. If a Christian" +
"wrong a Jew, what should his sufferance be by" +
"Christian example? Why, revenge. The villany you" +
"teach me, I will execute, and it shall go hard but I" +
"will better the instruction.",
"Virtue! a fig! 'tis in ourselves that we are thus" +
"or thus. Our bodies are our gardens, to the which" +
"our wills are gardeners: so that if we will plant" +
"nettles, or sow lettuce, set hyssop and weed up" +
"thyme, supply it with one gender of herbs, or" +
"distract it with many, either to have it sterile" +
"with idleness, or manured with industry, why, the" +
"power and corrigible authority of this lies in our" +
"wills. If the balance of our lives had not one" +
"scale of reason to poise another of sensuality, the" +
"blood and baseness of our natures would conduct us" +
"to most preposterous conclusions: but we have" +
"reason to cool our raging motions, our carnal" +
"stings, our unbitted lusts, whereof I take this that" +
"you call love to be a sect or scion.",
"Blow, winds, and crack your cheeks! rage! blow!" +
"You cataracts and hurricanoes, spout" +
"Till you have drench'd our steeples, drown'd the cocks!" +
"You sulphurous and thought-executing fires," +
"Vaunt-couriers to oak-cleaving thunderbolts," +
"Singe my white head! And thou, all-shaking thunder," +
"Smite flat the thick rotundity o' the world!" +
"Crack nature's moulds, an germens spill at once," +
"That make ingrateful man!"
};
}
/**
* We will use a SpeechView to display each speech. It's just a LinearLayout
* with two text fields.
*
*/
private class SpeechView extends LinearLayout {
public SpeechView(Context context, String title, String words) {
super(context);
this.setOrientation(VERTICAL);
// Here we build the child views in code. They could also have
// been specified in an XML file.
mTitle = new TextView(context);
mTitle.setText(title);
addView(mTitle, new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
mDialogue = new TextView(context);
mDialogue.setText(words);
addView(mDialogue, new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
}
/**
* Convenience method to set the title of a SpeechView
*/
public void setTitle(String title) {
mTitle.setText(title);
}
/**
* Convenience method to set the dialogue of a SpeechView
*/
public void setDialogue(String words) {
mDialogue.setText(words);
}
private TextView mTitle;
private TextView mDialogue;
}
}

该例子中自定义了适配器 SpeechListAdapter (其继承父类BaseAdapter)以及作为记录模板的 SpeechView(其父类为LinearLayout)。
SpeechListAdapter中的方法getView实现了返回指定位置的记录显示对象的逻辑。

(0)

相关推荐

  • Android编程中常用适配器及自定义适配器用法实例分析

    本文实例讲述了Android编程中常用适配器及自定义适配器用法.分享给大家供大家参考,具体如下: 一.适配器. 顾名思义,就是把一些数据给弄得适当,适合以便于在View上显示.可以看作是界面数据绑定的一种理解.它所操纵的数据一般都是一些比较复杂的数据,如数组,链表,数据库,集合等.适配器就像显示器,把复杂的东西按人可以接受的方式来展现. 那么适配器是怎么处理得到的数据,并把它显示出来的呢.其实很简单,说白了适配器它也是一个类,在类里面它实现了父类的这几个方法: publicint getCoun

  • Android 适配器模式应用及设计原理

    适配器模式是一种重要的设计模式,在 Android 中得到了广泛的应用.适配器类似于现实世界里面的插头,通过适配器,我们可以将分属于不同类的两种不同类型的数据整合起来,而不必去根据某一需要增加或者修改类里面的方法. 适配器又分为单向适配器和双向适配器,在 android 中前者使用的比较频繁.比较常见的实现方式是:首先定义一个适配类,内部定义一个私有的需要适配的对象,该类提供一个构造函数,将该对象的一个实例作为参数传入,并在构造函数里面进行初始化,再提供一个公有的方法,返回另外一个需要适配的类所

  • Android之自定义实现BaseAdapter(通用适配器一)

    通过前面的优化布局之后,我们接着来讲如何打造一个通用的适配器,那么通用适配器能干吗呢?很简单,减少我们对代码的书写,下面开始上代码了. MyAdapter.java public class MyAdapter extends BaseAdapter { private List<Student> data; public MyAdapter(List<Student> data) { this.data = data; } @Override public int getCoun

  • 举例讲解Android应用中SimpleAdapter简单适配器的使用

    SimpleAdapter,跟名字一样,一个简单的适配器,既为简单,就只是被设计来做简单的应用的,比如静态数据的绑定,不过仍然有自定义的空间,比如说在每一个ListItem中加一个按钮并添加响应事件.首先还是先看一下SimpleAdapter的定义吧,直接翻译下SDK doc 吧: 这是一个简单的适配器,可以将静态数据映射到XML文件中定义好的视图.你可以指定由Map组成的List(比如ArrayList)类型的数据.在ArrayList中的每个条目对应List中的一行.Maps包含每一行的数据

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

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

  • Android中 自定义数据绑定适配器BaseAdapter的方法

    复制代码 代码如下: public class PersonAdapter extends BaseAdapter { private List persons;// 要绑定的数据 private int resource;// 绑定的一个条目界面的id,此例中即为item.xml private LayoutInflater inflater;// 布局填充器,它可以使用一个xml文件生成一个View对象,可以通过Context获取实例对象 public PersonAdapter(Conte

  • Android控件系列之相册Gallery&Adapter适配器入门&控件缩放动画入门

    学习目的: 1.掌握在Android中如何建立Gallery 2.初步理解Android适配器的原理 3.实现简单的控件缩放动画 简介: 1.Gallery是Android内置的一个控件,它可以继承若干图片甚至是其他控件 2.Gallery自带了滚动播放图片功能,此功能您可以通过模拟器拖曳鼠标或者在手机上拖拽验证 3.Gallery需要适配器来传输数据,如果您不熟悉"适配器设计模式",可以将适配器理解为某厂商的电脑适配器,只要这个厂商的所有型号的电脑都能使用该适配器,也就是说,设计新型

  • 学习Android自定义Spinner适配器

    本文为大家分享Android自定义Spinner适配器的相关知识点,供大家参考,具体内容如下 一.大致效果 二.关键代码 在注释中讲重点吧. (1)Spinner的布局: car_brand_spinner.xml 即为弹出来的下拉列表的布局啦,后面的那个布局就不拿出来丢人现眼了,反正知道有一个Spinner的id为carBrandSpinner就可以了. <?xml version="1.0" encoding="utf-8"?> <Linear

  • Android之自定义实现BaseAdapter(通用适配器二)

    在上一篇通用适配器一中,我们已经把ViewHolder抽取为了一个通用的持有类,极大程度上减少了我们对代码的书写,现在开始在那样的基础上在此抽取,从而达到更优.先回顾上一篇中的MyAdapter.java类中的代码,然后通过这个代码我们再一次抽取封装. public class MyAdapter extends MyBaseAdapter { public MyAdapter(List<Student> data) { super(data); } @Override public View

  • Android列表实现(3)_自定义列表适配器思路及实现代码

    下面的例子为使用自定义的列表适配器来显示列表. 复制代码 代码如下: View Code import android.os.Bundle; import android.app.ListActivity; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.

  • Android列表实现(1)_数组列表实例介绍

    最近开始学习android的ui,先上几个相关的例子,后续还会有更新. 复制代码 代码如下: import android.app.ListActivity; import android.os.Bundle; import android.widget.ArrayAdapter; /** * A list view example where the * data for the list comes from an array of strings. */ public class List

  • Android列表实现(2)_游标列表案例讲解

    复制代码 代码如下: import android.app.ListActivity; import android.database.Cursor; import android.os.Bundle; import android.provider.Contacts.Phones; import android.widget.ListAdapter; import android.widget.SimpleCursorAdapter; /** * A list view example whe

  • Android Scroll实现弹性滑动_列表下拉弹性滑动的示例代码

    我这一次讲使用scroll实现弹性滑动,我不会只有一个例子就说完,因为写文章的时候我也在学习,我分几次讲完吧. 首先上一段代码, private void smoothScrollByScroller(int dy){ mScroller.startScroll(0,dy,0,dy*-1,1000); invalidate(); } @Override public void computeScroll() { if (mScroller.computeScrollOffset()) { scr

  • android 有阻尼下拉刷新列表的实现方法

    本文将会介绍有阻尼下拉刷新列表的实现,先来看看效果预览: 这是下拉状态: 这是下拉松开手指后listView回滚到刷新状态时的样子: 1. 如何调用 虽然效果图看起来样子不太好看,主要是因为那个蓝色的背景对不对,没关系,这只是一个背景而已,在了解了我们这个下拉刷新列表的实现之后,你就可以很轻松地修改这个背景,从而实现你想要的UI效果!话不多说,下面我们先来讲讲这个下拉刷新列表是如何使用的,这也是我们编写代码所要实现的目标. final PullToRefreshListView eListVie

  • Android Jetpack Compose无限加载列表

    目录 前言 方法一: paging-compose 方法二:自定义实现 添加 LoadingIndicator 总结 前言 Android 中使用 ListView 或者 RecycleView 经常有滚动到底部自动 LoadMore 的需求,那么在 Compose 中该如何实现呢? 两种方法可供选择: 基于 paging-compose 自定义实现 方法一: paging-compose Jetpack 的 Paging 组件提供了对 Compose 的支持 dependencies { ..

  • Android实现recyclerview城市字母索引列表

    转拼音的依赖 implementation 'com.github.SilenceDut:jpinyin:v1.0' FastIndexView实现列表右侧字母索引列表 public class FastIndexView extends View { private static final String INDEX_NAME = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ"; private OnLetterUpdateListener listener; priva

  • Android基于BaseExpandableListAdapter实现的二级列表仿通话记录功能详解

    本文实例讲述了Android基于BaseExpandableListAdapter实现的二级列表仿通话记录功能.分享给大家供大家参考,具体如下: android SDK中带有这样类似的例子,但是那个还是静态数据,没有实际应用价值,参考意义不大. 网上找了很多,还是那样的情况,几乎是同一篇文章,大家转来转去.况且,那篇例子也是静态的数据. 还是自己试试,自己写一个吧.程序读取手机系统的通话记录,按联系人分组,显示到列表. 开发工具:eclipse 运行环境:htc G9 android2.3.3

  • Android使用AlertDialog实现的信息列表单选、多选对话框功能

    在使用AlertDialog实现单选和多选对话框时,分别设置setSingleChoiceItems()和setMultiChoiceItems()函数. 下面看主要的代码: 数据源数组: <resources> <!--单选--> <string-array name="arr_weather"> <item >晴</item> <item >多云</item> <item >小雨<

随机推荐