listview选中某一行,选中行高亮显示

//1. 在listView的clickListener中把选中的position传到Adapter的setSelectItem()方法中,并刷新Adapter
		mMenuItem.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView parent, View view, int position, long id) {
				mAdapter.setSelectItem(position);  
				mAdapter.notifyDataSetChanged();
			}
		});



public class MenuItemAdapter extends BaseAdapter {

	private int[] imageItems;
	private String[] textviewItems;
	private Context context;
        // 2. 定义selectItem变量
	private int selectItem = -1;

	public MenuItemAdapter(int[] imageItems, String[] textviewItems, Context context) {
		this.imageItems = imageItems;
		this.textviewItems = textviewItems;
		this.context = context;
	}

	@Override
	public int getCount() {
		return imageItems.length;
	}

	@Override
	public Object getItem(int position) {
		return imageItems[position];
	}

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

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder = null;
		if (convertView == null) {
			convertView = View.inflate(context, R.layout.layout_menu_items, null);
			holder = new ViewHolder();
			holder.iv = (ImageView) convertView.findViewById(R.id.iv_menu_item);
			holder.tv = (TextView) convertView.findViewById(R.id.tv_menu_item);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		holder.tv.setText(textviewItems[position]);
		holder.iv.setImageResource(imageItems[position]);

        // 4.判断position是否和selectItem相等
        if (position == selectItem) {  
            convertView.setBackgroundColor(Color.GRAY);  
        }   
        else {  
            convertView.setBackgroundColor(Color.TRANSPARENT);  
        }  

		return convertView;
	}

	class ViewHolder {
		TextView tv = null;
		ImageView iv = null;
	}
        // 3.listView的position传到变量selectItem中
	public void setSelectItem(int selectItem) {
		this.selectItem = selectItem;
	}

}


你可能感兴趣的:(Android)