1.实现如图所示的单选效果
由于Android提供的单选按钮radiobutton只能单行或单列显示,且样式并不美观,故可用GridView进行改造,实现单选效果,而要实现这样的效果重点就在GridView的适配器这块了。
首先是GridView的item的XML:
里边很简单,就只用来放显示选中效果的imageView和文字的textView 接下来是适配器:
public class GridViewRadioAdapter extends BaseAdapter { private Context mContext; private int lastPosition = -1; //记录上一次选中的图片位置,默认不选中 private String[] str = null; //放问题内容文字的数组 public GridViewRadioAdapter(Context mContext) { this.mContext = mContext; } public void setStr(String[] str){ //在activity中调用此方法传入问题的数组 this.str = str; } public void setSelection(int position) { //在activity中GridView的onItemClickListener中调用此方法,来设置选中位置 lastPosition = position; } @Override public int getCount() { return str.length; } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder = null; if (convertView == null){ viewHolder = new ViewHolder(); convertView = LayoutInflater.from(mContext).inflate(R.layout.adapter_gridview_radio_item, null); viewHolder.textView = (TextView) convertView.findViewById(R.id.textView); viewHolder.imageView = (ImageView) convertView.findViewById(R.id.imageView); viewHolder.relativeLayout = (RelativeLayout) convertView.findViewById(R.id.options); convertView.setTag(viewHolder); }else { viewHolder = (ViewHolder) convertView.getTag(); } viewHolder.textView.setText(str[position]); if (lastPosition == position){ //判断是否为选中项,选中项与非选中项设置不同的样式 switch (position){ //选中状态下设置样式 case 0: viewHolder.imageView.setBackgroundResource(R.drawable.option_a_checked); break; case 1: viewHolder.imageView.setBackgroundResource(R.drawable.option_b_checked); break; case 2: viewHolder.imageView.setBackgroundResource(R.drawable.option_c_checked); break; case 3: viewHolder.imageView.setBackgroundResource(R.drawable.option_d_checked); break; } viewHolder.relativeLayout.setBackgroundResource(R.drawable.shape_rect_orange); }else { //非选中状态下设置样式 switch (position){ case 0: viewHolder.imageView.setBackgroundResource(R.drawable.option_a); break; case 1: viewHolder.imageView.setBackgroundResource(R.drawable.option_b); break; case 2: viewHolder.imageView.setBackgroundResource(R.drawable.option_c); break; case 3: viewHolder.imageView.setBackgroundResource(R.drawable.option_d); break; } viewHolder.relativeLayout.setBackgroundResource(R.drawable.shape_rect_gray); } return convertView; } class ViewHolder{ private TextView textView; private ImageView imageView; private RelativeLayout relativeLayout; } } 最后在activity中设置适配器:
GridViewRadioAdapter adapter = new GridViewRadioAdapter(mContext); adapter.setStr(options); //传入问题的选项 mGridView.setAdapter(adapter); mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView arg0, View arg1, int position, long arg3) { adapter.setSelection(position); //传值更新 adapter.notifyDataSetChanged(); //每一次点击通知adapter重新渲染 } });