在ListView的Item中使用RadioButton实现单选

在ListView的Item中使用RadioButton实现单选_第1张图片在ListView的Item中使用RadioButton实现单选_第2张图片

有时候要先上面的功能,listview的条目不光可以选择而且还要显示其他的信息,这个就需要两种方式进行监听,radiobutton实现单选,并且根据选择的item,知道选择的信息的核心代码如下:

  class MyAdapter extends BaseAdapter{

    	private LayoutInflater inflater;
    	private int temp = -1;
    	
    	public MyAdapter(Context context){
    		inflater = LayoutInflater.from(context);
    	}
    	
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return lists.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			
			/**/
			if(convertView == null){
				convertView = inflater.inflate(R.layout.getviewxml, null);
				viewHolder = new ViewHolder();
				viewHolder.rb = (RadioButton)convertView.findViewById(R.id.rb);
			
				convertView.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder)convertView.getTag();
			}
			
			
			viewHolder.position = position;
			viewHolder.rb.setId(position);
			viewHolder.rb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
				
				@Override
				public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
					if (arg1) {
						if (temp != -1) {
							/*为fadiobutton设置id,拿到该对象*/
							RadioButton tempRadio = (RadioButton) (MainActivity.this)
									.findViewById(temp);
							if (tempRadio != null) {
								tempRadio.setChecked(false);
							}
						}
						temp = arg0.getId();
						
					}
				}
			});
			/*下面的判断主要是解决item隐藏后又显示选中状态消除的问题*/
			if (position == temp) {
				viewHolder.rb.setChecked(true);
			} else {
				viewHolder.rb.setChecked(false);
			}
			
			return convertView;
		}
    	
    }
    
    static class ViewHolder{
    	RadioButton rb;
    	int position;
    }


你可能感兴趣的:(Android进阶部分)