ListView 资源整理

1.ListView中让onClick和onItemClick事件共存

将具有点击事件控件的android:focusable属性置成false就可以了。


2.listView的选中颜色
ListView选中时默认是黄色,很多时候会和我们软件的配色不符合,那么我就教你如何修改默认的ListView配色,改变ListView选中颜色有两个方法:

(1). 在程序中:

Java代码
  1. Drawabledrawable=getResources().getDrawable(R.drawable.touch_feedback);
  2. ListView.setSelector(drawable);

(2). 在xml里面的ListView标签下添加:
Java代码
  1. android:listSelector=”#00000000//后面的颜色可以自己定这样写是透明的



3.记录和恢复ListView滚动的位置

有时候我们需要记录当前ListView滚动到的位置,重新加载的时候要回到原位,不罗嗦,给出代码:

Java代码
  1. //列表滚动
  2. privateOnScrollListenerScrollLis=newOnScrollListener(){
  3. @Override
  4. publicvoidonScroll(AbsListViewarg0,intarg1,intarg2,intarg3){
  5. }
  6. @Override
  7. publicvoidonScrollStateChanged(AbsListViewview,intscrollState){
  8. if(scrollState==OnScrollListener.SCROLL_STATE_IDLE){
  9. ListPos=list.getFirstVisiblePosition();//ListPos记录当前可见的List顶端的一行的位置
  10. }
  11. }
  12. };


接下来就是还原位置,放在ListView加载之后:

Java代码
  1. list.setSelection(ListPos);



4.关于android ListView的美化

用心的朋友应该会发现,listview中在设置了背景之后。会有些问题。
1.、listview在拖动的时候背景图片消失变成黑色背景。等到拖动完毕我们自己的背景图片才显示出来。
2 、listview的上边和下边有黑色的阴影。
3、lsitview的每一项之间需要设置一个图片做为间隔。
针对以上问题 在listview的xml文件中设置一下语句。


问题1 有如下代码结解决 android:scrollingCache=”false” 或 android:cacheColorHint=”#00000000″
问题2 用如下代码解决:android:fadingEdge=”none”
问题3 用如下代码解决: android:divider=”@drawable/list_driver” 其中 @drawable/list_driver 是一个图片资源



5.ListView 中添加按钮,动态删除添加ItemView的操作

要实现添加按钮的操作,必须自定义Adapter,使用Button View的setTag()方法,将Button所属的位置设置到tag当中
要实现动态添加删除ItemView的操作,必须首先调整调整Adapter所绑定的数据源,然后调用Adapter的notifyDataSetChanged()方法

以下为实现的一个实例

Java代码
  1. packagecom.jason.joysmsyd;
  2. importjava.util.ArrayList;
  3. importjava.util.HashMap;
  4. importjava.util.List;
  5. importjava.util.Map;
  6. importandroid.app.ListActivity;
  7. importandroid.content.Intent;
  8. importandroid.os.Bundle;
  9. importandroid.view.LayoutInflater;
  10. importandroid.view.View;
  11. importandroid.view.ViewGroup;
  12. importandroid.view.Window;
  13. importandroid.view.View.OnClickListener;
  14. importandroid.widget.BaseAdapter;
  15. importandroid.widget.Button;
  16. importandroid.widget.EditText;
  17. importandroid.widget.TextView;
  18. publicclassSendMainextendsListActivityimplementsOnClickListener{
  19. ButtonbuttonMessage,buttonContact,buttonHistory;
  20. EditTexttextMessage;
  21. List<Map<String,String>>contacts=newArrayList<Map<String,String>>();
  22. @Override
  23. protectedvoidonCreate(BundlesavedInstanceState){
  24. //TODOAuto-generatedmethodstub
  25. super.onCreate(savedInstanceState);
  26. this.requestWindowFeature(Window.FEATURE_NO_TITLE);
  27. this.setContentView(R.layout.layout_send);
  28. buttonMessage=(Button)this.findViewById(R.id.ButtonMessage);
  29. buttonContact=(Button)this.findViewById(R.id.ButtonContact);
  30. buttonHistory=(Button)this.findViewById(R.id.ButtonHistory);
  31. textMessage=(EditText)this.findViewById(R.id.EditTextMessage);
  32. textMessage.setText(this.getIntent().getExtras().getString("message"));
  33. }
  34. publicvoidonClick(Viewv){
  35. //TODOAuto-generatedmethodstub
  36. switch(v.getId()){
  37. caseR.id.ButtonMessage:
  38. this.finish();
  39. break;
  40. caseR.id.ButtonContact:
  41. {
  42. Intentintent=newIntent();
  43. intent.setAction("com.jason.action.contact");
  44. this.startActivityForResult(intent,0);
  45. }
  46. break;
  47. caseR.id.ButtonHistory:
  48. {
  49. Intentintent=newIntent();
  50. intent.setAction("com.jason.action.history");
  51. this.startActivityForResult(intent,1);
  52. }
  53. break;
  54. }
  55. }
  56. protectedvoidonActivityResult(intrequestCode,intresultCode,Intentdata){
  57. //TODOAuto-generatedmethodstub
  58. super.onActivityResult(requestCode,resultCode,data);
  59. if(requestCode==0&&resultCode==RESULT_OK){
  60. this.getcontactFromString(data.getExtras().getString(
  61. UserSelectActivity.RETURN_LIST));
  62. bindDataToList();
  63. }
  64. }
  65. privatevoidgetcontactFromString(Stringdata){
  66. if(data==null||data.length()==0){
  67. return;
  68. }
  69. String[]arrayContact=data.split("#");
  70. for(StringsingleContact:arrayContact){
  71. if(singleContact!=null&&singleContact.length()>0){
  72. String[]props=singleContact.split(":");
  73. if(props.length==2){
  74. Map<String,String>contact=newHashMap<String,String>();
  75. contact.put("name",props[0]);
  76. contact.put("phone",props[1]);
  77. contacts.add(contact);
  78. }
  79. }
  80. }
  81. }
  82. privatevoidbindDataToList(){
  83. this.setListAdapter(newMyAdapter());
  84. }
  85. publicclassMyAdapterextendsBaseAdapter{
  86. publicintgetCount(){
  87. //TODOAuto-generatedmethodstub
  88. returncontacts.size();
  89. }
  90. publicObjectgetItem(intposition){
  91. //TODOAuto-generatedmethodstub
  92. returncontacts.get(position);
  93. }
  94. publiclonggetItemId(intposition){
  95. //TODOAuto-generatedmethodstub
  96. returnposition;
  97. }
  98. publicViewgetView(intposition,ViewconvertView,ViewGroupparent){
  99. //TODOAuto-generatedmethodstub
  100. LayoutInflaterinflater=SendMain.this.getLayoutInflater();
  101. finalViewview=inflater.inflate(R.layout.layout_user_item,null);
  102. finalTextViewtextPhone=(TextView)view.findViewById(R.id.text1);
  103. finalTextViewtextName=(TextView)view.findViewById(R.id.text2);
  104. Buttonbutton=(Button)view.findViewById(R.id.buttonDelete);
  105. textPhone.setText(contacts.get(position).get("phone"));
  106. textName.setText(contacts.get(position).get("name"));
  107. button.setTag(position);
  108. button.setOnClickListener(newOnClickListener(){
  109. publicvoidonClick(Viewv){
  110. //TODOAuto-generatedmethodstub
  111. intposition=Integer.parseInt(v.getTag().toString());
  112. contacts.remove(position);
  113. MyAdapter.this.notifyDataSetChanged();
  114. //SendMain.this.getListView().refreshDrawableState();
  115. }});
  116. returnview;
  117. }
  118. }
  119. }



6.Android ListView 清单与其Trigger 触发事件

Android ListView 清单与其选择时的触发事件,

可以参考下面的程式范例 :

Java代码
  1. publicclasshelloWorldextendsActivity{
  2. String[]vData=null;
  3. publicvoidonCreate(BundlesavedInstanceState){
  4. super.onCreate(savedInstanceState);
  5. //要做为ArrayAdapter的资料来源
  6. vData=newString[]{"足球","棒球","篮球"};
  7. //建立"阵列接收器"
  8. ArrayAdapter<String>arrayData=newArrayAdapter<String>(
  9. this
  10. ,android.R.layout.simple_list_item_1
  11. ,vData
  12. );
  13. //建立ListView物件
  14. ListViewlv=newListView(this);
  15. //设定ListView的接收器,做为选项的来源
  16. lv.setAdapter(arrayData);
  17. //ListView设定Trigger
  18. lv.setOnItemClickListener(newOnItemClickListener(){
  19. publicvoidonItemClick(AdapterView<?>arg0,Viewarg1,intarg2,
  20. longarg3){
  21. //TODOAuto-generatedmethodstub
  22. setTitle(getResources().getString(R.string.app_name)+":"+vData[arg2]);
  23. }
  24. });
  25. //设定ListView为ContentView
  26. setContentView(lv);
  27. }
  28. }







7.ListView内容刷新问题

最近在学习Android的listView控件时遇到了一个问题,如何添加一个Item到ListView中并及时的刷新出来。在网上查了很多帖子,很多人在问,也很多人在解答,但是总的来说都没找到详细的解决方案。对于ListView与数据库的同步,高手们建议使用ContentProvider对象。但是如果我不使用数据库呢?也有人回答用notifyDataSetChanged()方法。这倒是一个正确的解决方案,但是对于新手来说,还是比较困惑怎么去用,这里我贴一下我的用法:

Java代码
  1. OnClickListenerlistener2=newOnClickListener(){
  2. @Override
  3. publicvoidonClick(Viewv){
  4. //TODOAuto-generatedmethodstub
  5. Map<String,Object>m=newHashMap<String,Object>();
  6. StringtiString=tv.getText().toString();//注意这里我为什么要取出这个EditText的内容
  7. m.put("prod_na",tiString);//而不这样写m.put("prod_na",tv.getText());
  8. m.put("prod_type",tiString);//因为tv.getText()返回的是Editable对象,真正的数据是被缓存的,
  9. //也就是说你后续的EditText改动都会影响之前添加的Item
  10. coll.add(m);
  11. //取回Adapter对象,用于调用notifyDataSetChanged方法。
  12. SimpleAdaptersAdapter=(SimpleAdapter)lv.getAdapter();
  13. sAdapter.notifyDataSetChanged();
  14. }
  15. };


这里涉及到了Android中的MVC模式概念,如何存储数据,控制和显示。

你可以认为ListView是一个View,那么mode是什么呢?显然是SimpleAdapter对象,而Control又是什么呢?那只能是notifyDataSetChanged()了。当数据变化时,也就是SimpleAdapter所处理的数据变化了,那么我们就需要调用 notifyDataSetChanged 去通知View作出改变。


8.checkBox的显示和隐藏。

在listView中,每个item都有一个ChexBox,当显示的时候在listView外面设置一个按钮,点击显示和隐藏listView中所有的checBox;

开始的我的实现方法为:

Button add = (Button)findViewById(R.id.add);
add.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {

if(flage){checkBox.setVisibility(View.VISIBLE);flage=!flage;}
else{checkBox.setVisibility(View.GONE);flage=!flage;}
}
});

后来发现,只能改变listView中第一个checBox,对listView中其他的item不起作用。

以上做法不对,正确的做法是在Adapter中的getView中设置隐藏和显示,做法如下:

在getView中,

final CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBox);
if(flage){checkBox.setVisibility(View.VISIBLE);}
else{checkBox.setVisibility(View.GONE);}

然后在按钮点击事件中:

@Override
public void onClick(View v) {
flage=!flage;
mySubscriptionsListAdapt.notifyDataSetChanged();
}

notifyDataSetChanged();是实现listView刷新的功能,不需要再次加载整个listView。

源代码见:http://henzil.googlecode.com/svn/trunk/android.ListAsyncActivty/


10.ListView隔行设置颜色

Java代码
  1. importjava.util.HashMap;
  2. importjava.util.List;
  3. importandroid.content.Context;
  4. importandroid.view.View;
  5. importandroid.view.ViewGroup;
  6. importandroid.widget.SimpleAdapter;
  7. publicclassSpecialAdapterextendsSimpleAdapter{
  8. privateint[]colors=newint[]{0x30FF0000,0x300000FF};
  9. publicSpecialAdapter(Contextcontext,List<HashMap<String,String>>items,intresource,String[]from,int[]to){
  10. super(context,items,resource,from,to);
  11. }
  12. @Override
  13. publicViewgetView(intposition,ViewconvertView,ViewGroupparent){
  14. Viewview=super.getView(position,convertView,parent);
  15. intcolorPos=position%colors.length;
  16. view.setBackgroundColor(colors[colorPos]);
  17. returnview;
  18. }
  19. }

Java代码
  1. SpecialAdapteradapter=newSpecialAdapter(this,fillMaps,R.layout.grid_item,from,to);
  2. ...


11.ListView横向移动

publicclassMyListViewextendsLinearLayoutimplementsOnGestureListener{
privateGestureDetectormGestureDetector;
privateListViewmListView;

publicMyListView(Contextcontext){
super(context);
mGestureDetector
=newGestureDetector(this);
mListView
=newListView(context);
String[]items
=createStrings();
mListView.setAdapter(
newArrayAdapter<String>(context,
android.R.layout.simple_list_item_single_choice,items));
mListView.setCacheColorHint(Color.TRANSPARENT);
mListView.setScrollBarStyle(SCROLLBARS_OUTSIDE_INSET);
mListView.setOnItemClickListener(
newOnItemClickListener(){
@Override
publicvoidonItemClick(AdapterView<?>arg0,Viewarg1,intarg2,
longarg3){
Log.i(
"info","click");
}
});
this.addView(mListView,newLinearLayout.LayoutParams(350,LayoutParams.FILL_PARENT));
}

@Override
publicbooleanonDown(MotionEventarg0){
returnfalse;
}

@Override
publicbooleanonFling(MotionEvente1,MotionEvente2,floatvelocityX,
floatvelocityY){
returntrue;
}

@Override
publicvoidonLongPress(MotionEvente){
//empty
}

@Override
publicbooleanonScroll(MotionEvente1,MotionEvente2,floatdistanceX,
floatdistanceY){
intscrollWidth=mListView.getWidth()-this.getWidth();
if((this.getScrollX()>=0)&&(this.getScrollX()<=scrollWidth)&&(scrollWidth>0)){
intmoveX=(int)distanceX;
if(((moveX+this.getScrollX())>=0)&&((Math.abs(moveX)+Math.abs(this.getScrollX()))<=scrollWidth)){
this.scrollBy(moveX,0);
}
else{
if(distanceX>=0){
this.scrollBy(scrollWidth-Math.max(Math.abs(moveX),Math.abs(this.getScrollX())),0);
}
else{
this.scrollBy(-Math.min(Math.abs(moveX),Math.abs(this.getScrollX())),0);
}
}
}
returntrue;
}

@Override
publicvoidonShowPress(MotionEvente){
//empty
}

@Override
publicbooleanonSingleTapUp(MotionEvente){
returnfalse;
}

@Override
publicbooleandispatchTouchEvent(MotionEventev){
mGestureDetector.onTouchEvent(ev);
super.dispatchTouchEvent(ev);
returntrue;
}

privateString[]createStrings(){
returnnewString[]{
"AbbayedeBelloc","AbbayeduMontdesCats","Abertam","Abondance","Ackawi",
"Acorn","Adelost","AffideliceauChablis","Afuega'lPitu","Airag","Airedale",
"AisyCendre","AllgauerEmmentaler","Alverca","Ambert","AmericanCheese",
"AmiduChambertin","AnejoEnchilado","AnneauduVic-Bilh","Anthoriro","Appenzell",
"Aragon","ArdiGasna","Ardrahan","ArmenianString","AromesauGenedeMarc",
"Asadero","Asiago","AubisquePyrenees","Autun","Avaxtskyr","BabySwiss",
"Babybel","BaguetteLaonnaise","Bakers","Baladi","Balaton","Bandal","Banon",
"Barry'sBayCheddar","Basing","BasketCheese","BathCheese","BavarianBergkase",
"Baylough","Beaufort","Beauvoorde","BeenleighBlue","BeerCheese","BelPaese",
"Bergader","BergereBleue","Berkswell","BeyazPeynir","Bierkase","BishopKennedy",
"Blarney","Bleud'Auvergne","BleudeGex","BleudeLaqueuille",
"BleudeSeptmoncel","BleuDesCausses","Blue","BlueCastello","BlueRathgore",
"BlueVein(Australian)","BlueVeinCheeses","Bocconcini","Bocconcini(Australian)",
"BoerenLeidenkaas","Bonchester","Bosworth","Bougon","BouleDuRoves",
"Bouletted'Avesnes","Boursault","Boursin","Bouyssou","Bra","Braudostur",
"BreakfastCheese","BrebisduLavort","BrebisduLochois","BrebisduPuyfaucon",
"BresseBleu","Brick","Brie","BriedeMeaux","BriedeMelun","Brillat-Savarin",
"Brin","Brind'Amour","Brind'Amour","Brinza(BurdufBrinza)",
"BriquettedeBrebis","BriquetteduForez","Broccio","BroccioDemi-Affine",
"BrousseduRove","BruderBasil","BrusselaeKaas(FromagedeBruxelles)","Bryndza",
"Buchetted'Anjou","Buffalo","Burgos","Butte","Butterkase","Button(Innes)",

"BuxtonBlue","Cabecou","Caboc","Cabrales","Cachaille","Caciocavallo"

转自:http://blog.csdn.net/skydsai/article/details/6745277

你可能感兴趣的:(ListView)