RadioButton在我们开发APP应用中是很常见的.这点我不用说大家也心知肚明.
虽说Android 系统给我们提供了RadioButton但是为了我们的应用有种"与众不同"的效果,因为android的太死板太斯通见惯了.往往都会定制自己的图标.下面我给大家介绍一下我实现的方法:
方法:运用组合控件(ImageView and TextView)
组合控件代码:
/***
* 组合控件
*
* @author zhangjia
*
*/
public class RadioButton extends LinearLayout {
private Context context;
private ImageView imageView;
private TextView textView;
private int index = 0;
private int id = 0;// 判断是否选中
private RadioButton tempRadioButton;// 模版用于保存上次点击的对象
private int state[] = { R.drawable.radio_unchecked,
R.drawable.radio_checked };
/***
* 改变图片
*/
public void ChageImage() {
index++;
id = index % 2;// 获取图片id
imageView.setImageResource(state[id]);
}
/***
* 设置文本
*
* @param text
*/
public void setText(String text) {
textView.setText(text);
}
public String getText() {
return id == 0 ? "" : textView.getText().toString();
}
public RadioButton(Context context) {
this(context, null);
}
public RadioButton(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
LayoutInflater.from(context).inflate(R.layout.item, this, true);
imageView = (ImageView) findViewById(R.id.iv_item);
textView = (TextView) findViewById(R.id.tv_item);
}
}
上面的实现的很容易,所以不过多解释.
下面是调用代码:
public class MainActivity extends Activity {
ListView listView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listView = (ListView) findViewById(R.id.lv_main);
listView.setAdapter(new MyAdapter(this));
}
/***
* @author jia
*/
RadioButton temp;
class MyAdapter extends BaseAdapter {
private Context context;
private LayoutInflater inflater;
public MyAdapter(Context context) {
super();
this.context = context;
inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return 10;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final RadioButton radioButton;
if (convertView == null) {
radioButton = new RadioButton(context);
} else {
radioButton = (RadioButton) convertView;
}
radioButton.setText(position + "");
radioButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 模版不为空,则chage.
if (temp != null) {
temp.ChageImage();
}
temp = radioButton;
radioButton.ChageImage();
Toast.makeText(context, radioButton.getText(), 1000).show();
}
});
return radioButton;
}
}
}
我来说明一下:我们首先创建一个temp模版,用于记忆你点击的那个RadioButton对象. 在你点击时候,首先查看temp是否为null,如果不为空则执行 temp.ChageImage(); 这个方法是取消选中效果.如果不为null,则首