1.ListView中让onClick和onItemClick事件共存
将具有点击事件控件的android:focusable属性置成false就可以了。
2.listView的选中颜色
ListView选中时默认是黄色,很多时候会和我们软件的配色不符合,那么我就教你如何修改默认的ListView配色,改变ListView选中颜色有两个方法:
(1). 在程序中:
- Drawabledrawable=getResources().getDrawable(R.drawable.touch_feedback);
- ListView.setSelector(drawable);
(2). 在xml里面的ListView标签下添加:
- android:listSelector=”#00000000″//后面的颜色可以自己定这样写是透明的
3.记录和恢复ListView滚动的位置
有时候我们需要记录当前ListView滚动到的位置,重新加载的时候要回到原位,不罗嗦,给出代码:
- //列表滚动
- privateOnScrollListenerScrollLis=newOnScrollListener(){
-
- @Override
- publicvoidonScroll(AbsListViewarg0,intarg1,intarg2,intarg3){
- }
-
- @Override
- publicvoidonScrollStateChanged(AbsListViewview,intscrollState){
- if(scrollState==OnScrollListener.SCROLL_STATE_IDLE){
- ListPos=list.getFirstVisiblePosition();//ListPos记录当前可见的List顶端的一行的位置
- }
- }
- };
接下来就是还原位置,放在ListView加载之后:
- 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()方法
以下为实现的一个实例
- packagecom.jason.joysmsyd;
-
- importjava.util.ArrayList;
- importjava.util.HashMap;
- importjava.util.List;
- importjava.util.Map;
-
- importandroid.app.ListActivity;
- importandroid.content.Intent;
- importandroid.os.Bundle;
- importandroid.view.LayoutInflater;
- importandroid.view.View;
- importandroid.view.ViewGroup;
- importandroid.view.Window;
- importandroid.view.View.OnClickListener;
- importandroid.widget.BaseAdapter;
- importandroid.widget.Button;
- importandroid.widget.EditText;
- importandroid.widget.TextView;
-
- publicclassSendMainextendsListActivityimplementsOnClickListener{
-
- ButtonbuttonMessage,buttonContact,buttonHistory;
- EditTexttextMessage;
-
- List<Map<String,String>>contacts=newArrayList<Map<String,String>>();
-
-
-
- @Override
- protectedvoidonCreate(BundlesavedInstanceState){
- //TODOAuto-generatedmethodstub
- super.onCreate(savedInstanceState);
- this.requestWindowFeature(Window.FEATURE_NO_TITLE);
-
- this.setContentView(R.layout.layout_send);
-
- buttonMessage=(Button)this.findViewById(R.id.ButtonMessage);
- buttonContact=(Button)this.findViewById(R.id.ButtonContact);
- buttonHistory=(Button)this.findViewById(R.id.ButtonHistory);
-
- textMessage=(EditText)this.findViewById(R.id.EditTextMessage);
- textMessage.setText(this.getIntent().getExtras().getString("message"));
-
- }
-
- publicvoidonClick(Viewv){
- //TODOAuto-generatedmethodstub
- switch(v.getId()){
- caseR.id.ButtonMessage:
- this.finish();
- break;
- caseR.id.ButtonContact:
- {
- Intentintent=newIntent();
- intent.setAction("com.jason.action.contact");
- this.startActivityForResult(intent,0);
- }
- break;
- caseR.id.ButtonHistory:
- {
- Intentintent=newIntent();
- intent.setAction("com.jason.action.history");
- this.startActivityForResult(intent,1);
- }
- break;
- }
-
- }
-
-
- protectedvoidonActivityResult(intrequestCode,intresultCode,Intentdata){
- //TODOAuto-generatedmethodstub
- super.onActivityResult(requestCode,resultCode,data);
- if(requestCode==0&&resultCode==RESULT_OK){
- this.getcontactFromString(data.getExtras().getString(
- UserSelectActivity.RETURN_LIST));
- bindDataToList();
- }
- }
-
- privatevoidgetcontactFromString(Stringdata){
- if(data==null||data.length()==0){
- return;
- }
-
-
- String[]arrayContact=data.split("#");
- for(StringsingleContact:arrayContact){
- if(singleContact!=null&&singleContact.length()>0){
- String[]props=singleContact.split(":");
- if(props.length==2){
- Map<String,String>contact=newHashMap<String,String>();
- contact.put("name",props[0]);
- contact.put("phone",props[1]);
- contacts.add(contact);
-
- }
- }
-
- }
-
- }
-
- privatevoidbindDataToList(){
- this.setListAdapter(newMyAdapter());
- }
-
- publicclassMyAdapterextendsBaseAdapter{
-
- publicintgetCount(){
- //TODOAuto-generatedmethodstub
- returncontacts.size();
- }
-
- publicObjectgetItem(intposition){
- //TODOAuto-generatedmethodstub
- returncontacts.get(position);
- }
-
- publiclonggetItemId(intposition){
- //TODOAuto-generatedmethodstub
- returnposition;
- }
-
-
- publicViewgetView(intposition,ViewconvertView,ViewGroupparent){
- //TODOAuto-generatedmethodstub
- LayoutInflaterinflater=SendMain.this.getLayoutInflater();
- finalViewview=inflater.inflate(R.layout.layout_user_item,null);
- finalTextViewtextPhone=(TextView)view.findViewById(R.id.text1);
- finalTextViewtextName=(TextView)view.findViewById(R.id.text2);
- Buttonbutton=(Button)view.findViewById(R.id.buttonDelete);
-
- textPhone.setText(contacts.get(position).get("phone"));
- textName.setText(contacts.get(position).get("name"));
-
- button.setTag(position);
-
- button.setOnClickListener(newOnClickListener(){
-
- publicvoidonClick(Viewv){
- //TODOAuto-generatedmethodstub
- intposition=Integer.parseInt(v.getTag().toString());
- contacts.remove(position);
- MyAdapter.this.notifyDataSetChanged();
-
- //SendMain.this.getListView().refreshDrawableState();
- }});
-
-
-
-
- returnview;
- }
-
- }
- }
6.Android ListView 清单与其Trigger 触发事件
Android ListView 清单与其选择时的触发事件,
可以参考下面的程式范例 :
- publicclasshelloWorldextendsActivity{
-
- String[]vData=null;
-
- publicvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
-
- //要做为ArrayAdapter的资料来源
- vData=newString[]{"足球","棒球","篮球"};
-
- //建立"阵列接收器"
- ArrayAdapter<String>arrayData=newArrayAdapter<String>(
- this
- ,android.R.layout.simple_list_item_1
- ,vData
- );
-
- //建立ListView物件
- ListViewlv=newListView(this);
-
- //设定ListView的接收器,做为选项的来源
- lv.setAdapter(arrayData);
-
- //ListView设定Trigger
- lv.setOnItemClickListener(newOnItemClickListener(){
-
- publicvoidonItemClick(AdapterView<?>arg0,Viewarg1,intarg2,
- longarg3){
- //TODOAuto-generatedmethodstub
- setTitle(getResources().getString(R.string.app_name)+":"+vData[arg2]);
- }
- });
-
- //设定ListView为ContentView
- setContentView(lv);
- }
- }
7.ListView内容刷新问题
最近在学习Android的listView控件时遇到了一个问题,如何添加一个Item到ListView中并及时的刷新出来。在网上查了很多帖子,很多人在问,也很多人在解答,但是总的来说都没找到详细的解决方案。对于ListView与数据库的同步,高手们建议使用ContentProvider对象。但是如果我不使用数据库呢?也有人回答用notifyDataSetChanged()方法。这倒是一个正确的解决方案,但是对于新手来说,还是比较困惑怎么去用,这里我贴一下我的用法:
- OnClickListenerlistener2=newOnClickListener(){
- @Override
- publicvoidonClick(Viewv){
- //TODOAuto-generatedmethodstub
- Map<String,Object>m=newHashMap<String,Object>();
- StringtiString=tv.getText().toString();//注意这里我为什么要取出这个EditText的内容
- m.put("prod_na",tiString);//而不这样写m.put("prod_na",tv.getText());
- m.put("prod_type",tiString);//因为tv.getText()返回的是Editable对象,真正的数据是被缓存的,
- //也就是说你后续的EditText改动都会影响之前添加的Item
- coll.add(m);
-
- //取回Adapter对象,用于调用notifyDataSetChanged方法。
- SimpleAdaptersAdapter=(SimpleAdapter)lv.getAdapter();
- sAdapter.notifyDataSetChanged();
- }
- };
这里涉及到了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隔行设置颜色
- importjava.util.HashMap;
- importjava.util.List;
-
- importandroid.content.Context;
- importandroid.view.View;
- importandroid.view.ViewGroup;
- importandroid.widget.SimpleAdapter;
-
- publicclassSpecialAdapterextendsSimpleAdapter{
- privateint[]colors=newint[]{0x30FF0000,0x300000FF};
-
- publicSpecialAdapter(Contextcontext,List<HashMap<String,String>>items,intresource,String[]from,int[]to){
- super(context,items,resource,from,to);
- }
-
- @Override
- publicViewgetView(intposition,ViewconvertView,ViewGroupparent){
- Viewview=super.getView(position,convertView,parent);
- intcolorPos=position%colors.length;
- view.setBackgroundColor(colors[colorPos]);
- returnview;
- }
- }
- SpecialAdapteradapter=newSpecialAdapter(this,fillMaps,R.layout.grid_item,from,to);
- ...
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