欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2023-12-05 17:02:58
下面的例子为使用自定义的列表适配器来显示列表。 复制代码 代码如下: view code import android.os.bundle; import android....
下面的例子为使用自定义的列表适配器来显示列表。
复制代码 代码如下:

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实现了返回指定位置的记录显示对象的逻辑。