Android 自定义RadioButton(单选按钮)图标随便定
Android 自定义RadioButton(单选按钮)图标随便定
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;
- }
- }
- }
效果:
效果是实现了,不过有个小问题,因为目前只有10条数据是看不出效果的.换成20条你就会发现很诡异的问题。
图“:
第15条数据会自动勾选上,找了又找,最后终于发现了,是因为listview 的问题。看下面:
- final RadioButton radioButton;
- if (convertView == null) {
- radioButton = new RadioButton(context);
- } else {
- radioButton = (RadioButton) convertView;
- }
|
评论暂时关闭