listview点击一行高亮

 有时候在点击listview一个item时,为了让用户知道点击是那一行了,那就被点击的一行背景颜色要和其他没有被点击的item区分开来,点击一个item,那item背景颜色就变色,这个怎么做呢,其实很简单,当listview点击事件时,可以得到一个position,代表是listview中那一个item被点击了,然后在adapter中的getView()方法中position相比较,凡是界面上的一定要在getView()方法中做操作,

package com.example.listview;

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class MainActivity extends Activity {
	private ListView listview;
	private ArrayList<String> datas;
	private LayoutInflater inflater;
	private MyAdapter adapter;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		listview = (ListView) findViewById(R.id.listview);
		inflater = LayoutInflater.from(this);
		initData();
		adapter = new MyAdapter();
		listview.setAdapter(adapter);
		
		listview.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				adapter.setClickPosition(position);
				adapter.notifyDataSetChanged();
			}
		});
	}
	private void initData() {
		datas = new ArrayList<String>();
		for(int i=0;i<100;i++){
			datas.add("我是item-------");
		}
	}
	
	class MyAdapter extends BaseAdapter{
		private int clickPosition = -1;
		
		
		public void setClickPosition(int clickPosition) {
			this.clickPosition = clickPosition;
		}

		@Override
		public int getCount() {
			return datas.size();
		}

		@Override
		public Object getItem(int arg0) {
			return datas.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}

		@Override
		public View getView(int position, View converView, ViewGroup arg2) {
			ViewHolder holder = null;
			if(converView==null){
				converView = inflater.inflate(R.layout.item, null);
				holder = new ViewHolder();
				holder.tvContent = (TextView) converView.findViewById(R.id.tvContent);
				holder.rlRoot = (RelativeLayout) converView.findViewById(R.id.rlRoot);
			    converView.setTag(holder);
			}else{
				holder = (ViewHolder) converView.getTag();
			}
			if(clickPosition==position){
				holder.rlRoot.setBackgroundColor(getResources().getColor(R.color.click_chang_color));
			}else{
				holder.rlRoot.setBackgroundColor(getResources().getColor(R.color.white));
			}
			holder.tvContent.setText(datas.get(position));
			return converView;
		}
		
		class ViewHolder{
			TextView tvContent;
			RelativeLayout rlRoot;
		}
	}
}

效果:

listview点击一行高亮_第1张图片

你可能感兴趣的:(listview点击一行高亮)