ListView应用

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

1. 在程序中:
Java代码 复制代码  收藏代码
  1. Drawable drawable=getResources().getDrawable(R.drawable.touch_feedback);   
  2. ListView.setSelector(drawable);  
Drawable drawable=getResources().getDrawable(R.drawable.touch_feedback);
ListView.setSelector(drawable);



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



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

Java代码 复制代码  收藏代码
  1. //列表滚动   
  2. private OnScrollListener ScrollLis = new OnScrollListener() {   
  3.     
  4.     @Override  
  5.     public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {   
  6.     }   
  7.     
  8.     @Override  
  9.     public void onScrollStateChanged(AbsListView view, int scrollState) {   
  10.         if(scrollState==OnScrollListener.SCROLL_STATE_IDLE){   
  11.                     ListPos=list.getFirstVisiblePosition();  //ListPos记录当前可见的List顶端的一行的位置   
  12.             }   
  13.     }   
  14. };  
//列表滚动
private OnScrollListener ScrollLis = new OnScrollListener() {
 
	@Override
	public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
	}
 
	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		if(scrollState==OnScrollListener.SCROLL_STATE_IDLE){
                	ListPos=list.getFirstVisiblePosition();  //ListPos记录当前可见的List顶端的一行的位置
         	}
	}
};



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


Java代码 复制代码  收藏代码
  1. list.setSelection(ListPos);  
list.setSelection(ListPos);



关于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 是一个图片资源




ListView拖动时背景黑色的问题

我们知道在Android中ListView是一个比较常用的UI控件,我们在大部分开发中都需要用到它,因此Android为我们提供了ListView的多种实现方法,通过自定义显示布局让显示的内容更加美观,但是我们会发现这样一个问题,当我们操作ListView的时候,如果不使用手机上下按键的时候,直接用触摸拖动视图的方式,会发现ListView的背景一片黑色,而且所有被选中的文字都变成一片漆黑。

其实这个问题发生的原因在于ListView存在缓存颜色机制,因此我们可以通过设定缓存颜色为透明的方法来解决这个问题。ATAAW.COM提供两个解决方法供大家使用,如下所示:

A、通过布局属性来设定(ListView的属性中直接定义)

android:cacheColorHint=”#00000000″

B、在代码中直接设定

listView.setCacheColorHint(Color.TRANSPARENT);

这样就可以解决黑色出现的问题了。


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

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

以下为实现的一个实例

Java代码 复制代码  收藏代码
  1. package com.jason.joysmsyd;   
  2.     
  3. import java.util.ArrayList;   
  4. import java.util.HashMap;   
  5. import java.util.List;   
  6. import java.util.Map;   
  7.     
  8. import android.app.ListActivity;   
  9. import android.content.Intent;   
  10. import android.os.Bundle;   
  11. import android.view.LayoutInflater;   
  12. import android.view.View;   
  13. import android.view.ViewGroup;   
  14. import android.view.Window;   
  15. import android.view.View.OnClickListener;   
  16. import android.widget.BaseAdapter;   
  17. import android.widget.Button;   
  18. import android.widget.EditText;   
  19. import android.widget.TextView;   
  20.     
  21. public class SendMain extends ListActivity implements OnClickListener{   
  22.     
  23.     Button buttonMessage,buttonContact,buttonHistory;   
  24.     EditText textMessage;   
  25.     
  26.     List<Map<String,String>> contacts = new ArrayList<Map<String,String>>();   
  27.     
  28.     
  29.     
  30.     @Override  
  31.     protected void onCreate(Bundle savedInstanceState) {   
  32.         // TODO Auto-generated method stub   
  33.         super.onCreate(savedInstanceState);   
  34.         this.requestWindowFeature(Window.FEATURE_NO_TITLE);   
  35.     
  36.         this.setContentView(R.layout.layout_send);   
  37.     
  38.         buttonMessage = (Button) this.findViewById(R.id.ButtonMessage);   
  39.         buttonContact = (Button) this.findViewById(R.id.ButtonContact);   
  40.         buttonHistory = (Button) this.findViewById(R.id.ButtonHistory);   
  41.     
  42.         textMessage = (EditText)this.findViewById(R.id.EditTextMessage);   
  43.         textMessage.setText(this.getIntent().getExtras().getString("message"));   
  44.     
  45.     }   
  46.     
  47.     public void onClick(View v) {   
  48.         // TODO Auto-generated method stub   
  49.         switch(v.getId()){   
  50.         case R.id.ButtonMessage:   
  51.             this.finish();   
  52.             break;   
  53.         case R.id.ButtonContact:   
  54.         {   
  55.             Intent intent = new Intent();   
  56.             intent.setAction("com.jason.action.contact");   
  57.             this.startActivityForResult(intent, 0);   
  58.         }   
  59.             break;   
  60.         case R.id.ButtonHistory:   
  61.         {   
  62.             Intent intent = new Intent();   
  63.             intent.setAction("com.jason.action.history");   
  64.             this.startActivityForResult(intent, 1);   
  65.         }   
  66.             break;   
  67.         }   
  68.     
  69.     }   
  70.     
  71.     
  72.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {   
  73.         // TODO Auto-generated method stub   
  74.         super.onActivityResult(requestCode, resultCode, data);   
  75.          if (requestCode == 0 && resultCode == RESULT_OK) {   
  76.             this.getcontactFromString(data.getExtras().getString(   
  77.                     UserSelectActivity.RETURN_LIST));   
  78.             bindDataToList();   
  79.         }   
  80.     }   
  81.     
  82.     private void getcontactFromString(String data) {   
  83.         if (data == null || data.length() == 0) {   
  84.             return;   
  85.         }   
  86.     
  87.     
  88.         String[] arrayContact = data.split("#");   
  89.         for (String singleContact : arrayContact) {   
  90.             if (singleContact != null && singleContact.length() > 0) {   
  91.                 String[] props = singleContact.split(":");   
  92.                 if (props.length == 2) {   
  93.                     Map<String,String> contact = new HashMap<String,String>();   
  94.                     contact.put("name", props[0]);   
  95.                     contact.put("phone", props[1]);   
  96.                     contacts.add(contact);   
  97.     
  98.                 }   
  99.             }   
  100.     
  101.         }   
  102.     
  103.     }   
  104.     
  105.     private void bindDataToList(){   
  106.         this.setListAdapter(new MyAdapter());   
  107.     }   
  108.     
  109.     public class MyAdapter extends BaseAdapter{   
  110.     
  111.         public int getCount() {   
  112.             // TODO Auto-generated method stub   
  113.             return contacts.size();   
  114.         }   
  115.     
  116.         public Object getItem(int position) {   
  117.             // TODO Auto-generated method stub   
  118.             return contacts.get(position);   
  119.         }   
  120.     
  121.         public long getItemId(int position) {   
  122.             // TODO Auto-generated method stub   
  123.             return position;   
  124.         }   
  125.     
  126.     
  127.         public View getView(int position, View convertView, ViewGroup parent) {   
  128.             // TODO Auto-generated method stub   
  129.             LayoutInflater inflater = SendMain.this.getLayoutInflater();   
  130.              final View view = inflater.inflate(R.layout.layout_user_item, null);   
  131.              final TextView textPhone = (TextView) view.findViewById(R.id.text1);   
  132.              final TextView textName = (TextView) view.findViewById(R.id.text2);   
  133.              Button button = (Button)view.findViewById(R.id.buttonDelete);   
  134.     
  135.              textPhone.setText(contacts.get(position).get("phone"));   
  136.              textName.setText(contacts.get(position).get("name"));   
  137.     
  138.              button.setTag( position);   
  139.     
  140.              button.setOnClickListener(new OnClickListener(){   
  141.     
  142.                 public void onClick(View v) {   
  143.                     // TODO Auto-generated method stub   
  144.                     int position = Integer.parseInt(v.getTag().toString());   
  145.                     contacts.remove(position);   
  146.                     MyAdapter.this.notifyDataSetChanged();   
  147.     
  148. //                  SendMain.this.getListView().refreshDrawableState();   
  149.                 }});   
  150.     
  151.     
  152.     
  153.     
  154.             return view;   
  155.         }   
  156.     
  157.     }   
  158. }  
package com.jason.joysmsyd;
 
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
 
public class SendMain extends ListActivity implements OnClickListener{
 
	Button buttonMessage,buttonContact,buttonHistory;
	EditText textMessage;
 
	List<Map<String,String>> contacts = new ArrayList<Map<String,String>>();
 
 
 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		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"));
 
	}
 
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		case R.id.ButtonMessage:
			this.finish();
			break;
		case R.id.ButtonContact:
		{
			Intent intent = new Intent();
			intent.setAction("com.jason.action.contact");
			this.startActivityForResult(intent, 0);
		}
			break;
		case R.id.ButtonHistory:
		{
			Intent intent = new Intent();
			intent.setAction("com.jason.action.history");
			this.startActivityForResult(intent, 1);
		}
			break;
		}
 
	}
 
 
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		 if (requestCode == 0 && resultCode == RESULT_OK) {
			this.getcontactFromString(data.getExtras().getString(
					UserSelectActivity.RETURN_LIST));
			bindDataToList();
		}
	}
 
	private void getcontactFromString(String data) {
		if (data == null || data.length() == 0) {
			return;
		}
 
 
		String[] arrayContact = data.split("#");
		for (String singleContact : arrayContact) {
			if (singleContact != null && singleContact.length() > 0) {
				String[] props = singleContact.split(":");
				if (props.length == 2) {
					Map<String,String> contact = new HashMap<String,String>();
					contact.put("name", props[0]);
					contact.put("phone", props[1]);
					contacts.add(contact);
 
				}
			}
 
		}
 
	}
 
	private void bindDataToList(){
		this.setListAdapter(new MyAdapter());
	}
 
	public class MyAdapter extends BaseAdapter{
 
		public int getCount() {
			// TODO Auto-generated method stub
			return contacts.size();
		}
 
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return contacts.get(position);
		}
 
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}
 
 
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			LayoutInflater inflater = SendMain.this.getLayoutInflater();
			 final View view = inflater.inflate(R.layout.layout_user_item, null);
			 final TextView textPhone = (TextView) view.findViewById(R.id.text1);
			 final TextView textName = (TextView) view.findViewById(R.id.text2);
			 Button button = (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(new OnClickListener(){
 
				public void onClick(View v) {
					// TODO Auto-generated method stub
					int position = Integer.parseInt(v.getTag().toString());
					contacts.remove(position);
					MyAdapter.this.notifyDataSetChanged();
 
//					SendMain.this.getListView().refreshDrawableState();
				}});
 
 
 
 
			return view;
		}
 
	}
}



Android ListView 清单与其Trigger 触发事件

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

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

Java代码 复制代码  收藏代码
  1. public class helloWorld extends Activity {   
  2.     
  3.     String[] vData = null;   
  4.     
  5.     public void onCreate(Bundle savedInstanceState) {   
  6.         super.onCreate(savedInstanceState);   
  7.     
  8.         // 要做为ArrayAdapter的资料来源   
  9.         vData = new String[]{"足球","棒球","篮球"};   
  10.     
  11.         // 建立"阵列接收器"   
  12.         ArrayAdapter<String>  arrayData = new ArrayAdapter<String>(   
  13.                 this  
  14.                 , android.R.layout.simple_list_item_1   
  15.                 , vData   
  16.                 );   
  17.     
  18.         // 建立ListView 物件   
  19.         ListView  lv = new ListView(this);   
  20.     
  21.         // 设定ListView 的接收器, 做为选项的来源   
  22.         lv . setAdapter ( arrayData );   
  23.     
  24.         // ListView 设定Trigger   
  25.         lv . setOnItemClickListener ( new OnItemClickListener() {   
  26.     
  27.             public void onItemClick (AdapterView<?> arg0, View arg1, int arg2,   
  28.                     long arg3) {   
  29.                 // TODO Auto-generated method stub   
  30.                 setTitle( getResources().getString(R.string.app_name) + ": " + vData [ arg2 ]);   
  31.             }   
  32.         });   
  33.     
  34.         // 设定ListView 为ContentView   
  35.         setContentView(lv);   
  36.     }   
  37. }  
public class helloWorld extends Activity {
 
    String[] vData = null;
 
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 
        // 要做为ArrayAdapter的资料来源
        vData = new String[]{"足球","棒球","篮球"};
 
        // 建立"阵列接收器"
        ArrayAdapter<String>  arrayData = new ArrayAdapter<String>(
                this
                , android.R.layout.simple_list_item_1
                , vData
                );
 
        // 建立ListView 物件
        ListView  lv = new ListView(this);
 
        // 设定ListView 的接收器, 做为选项的来源
        lv . setAdapter ( arrayData );
 
        // ListView 设定Trigger
        lv . setOnItemClickListener ( new OnItemClickListener() {
 
            public void onItemClick (AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                // TODO Auto-generated method stub
                setTitle( getResources().getString(R.string.app_name) + ": " + vData [ arg2 ]);
            }
        });
 
        // 设定ListView 为ContentView
        setContentView(lv);
    }
}






Android中的ListView内容刷新问题

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

Java代码 复制代码  收藏代码
  1. OnClickListener listener2 = new OnClickListener() {   
  2.         @Override  
  3.         public void onClick(View v) {   
  4.             // TODO Auto-generated method stub   
  5.             Map<String, Object> m = new HashMap<String, Object>();   
  6.             String tiString  = 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.     
  12.             // 取回Adapter对象,用于调用notifyDataSetChanged方法。   
  13.             SimpleAdapter sAdapter = (SimpleAdapter)lv.getAdapter();   
  14.             sAdapter.notifyDataSetChanged();   
  15.         }   
  16.     };  
OnClickListener listener2 = new OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Map<String, Object> m = new HashMap<String, Object>();
            String tiString  = 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方法。
            SimpleAdapter sAdapter = (SimpleAdapter)lv.getAdapter();
            sAdapter.notifyDataSetChanged();
        }
    };


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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值