Android单选按钮自定义列

手里有个项目,看设计原型,像是使用单选按钮来实现选择条件,但是又是排列整齐的按钮。记得单选RadioGroup只有纵横排列,并不支持九宫格的排列,但是要实现九宫格的排列样式,也未尝不可,可以在<RaidoGroup>标签中使用其他的布局来辅助实现,只可惜这样做会留下一个很不爽的结果,同一行的RadioButton都变成了CheckedBox,可多选,很明显,这个并不是我们想要的结果。要解决这种窘境,也是有办法的,那就是用一个标志位,只允许选择一个按钮;只是博文里,我并不想用这种办法,一方面,控制麻烦,如果页面里有多个这样的布局,那个代码量可是相当的不爽,另一方面,我是新人,所以想尝试自定义控件来实现,以便累积点技能经验。(代码拙劣,大侠们请包涵,)

实现主要分为三部分,第一部分:自定义按钮;第二部分:自定义按钮容器;第三部分:按钮的背景。

首先,第一部分,代码:

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;

import cn.leungyong.app.R;

/**
 * 
 * Description:
 * Created by L.Y
 * Date:2015-10-20
 * Time:14:48
 * Copyright :c
 */
public class MyRadio extends Button implements View.OnTouchListener{

    private boolean isTouched = false;//是否被按下

    private int touch = 1;//按钮被按下的次数

    public MyRadio(Context context){
        super(context);
        init();
    }

    public MyRadio(Context context, AttributeSet attributeSet){
        super(context,attributeSet);
        init();
    }

    public MyRadio(Context context, AttributeSet attributeSet, int defStyle){
        super(context, attributeSet, defStyle);
        init();
    }

    protected void init(){
        setOnTouchListener(this);
    }

    public void setTouch(int touch){
        this.touch = touch;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if(0 == touch%2){
            this.setBackgroundResource(R.drawable.myradio_active);
        }else {
            this.setBackgroundResource(R.drawable.myradio_inactive);
        }
        invalidate();
    }

    public void setTouched(boolean isTouched){
        this.isTouched = isTouched;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                onValueChangedListner.OnValueChanged(this.getText().toString());
                isTouched = true;
                touch ++;
                break;
            case MotionEvent.ACTION_UP:
                isTouched = false;
                break;
        }
        return true;
    }

    public interface OnValueChangedListner{
        void OnValueChanged(String value);
    }

    //实现接口,方便将当前按钮的值回调
    OnValueChangedListner onValueChangedListner;

    public void setOnValueChangedListner(OnValueChangedListner onValueChangedListner){
        this.onValueChangedListner = onValueChangedListner;
    }
}
在按钮源码中,使用touch变量来记录当前按钮被按下的次数,同时实现Touch监听,以此来改变touch变量来改变按钮状态,重载OnDraw,在函数中修改按钮背景,接口OnValueChangedListener用于数据回调。

第二部分,容器:

import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Description:
 * Created by L.Y
 * Date:2015-10-20
 * Time:11:26
 * Copyright :
 */
public class ChoiceGroup extends LinearLayout {

    private int column = 0;//列数

    private int currentIndex = 0;//当前按钮下标

    private String currentValue = "";//当前按钮值

    private List<String> values = new ArrayList<>();//按钮文字列表

    private Map<Integer, Button> map = new HashMap<>();//按钮map

    public ChoiceGroup(Context context){
        super(context);
        init(context);
    }

    public ChoiceGroup(Context context,AttributeSet attributeSet){
        super(context,attributeSet);
        init(context);
    }

    public ChoiceGroup(Context context, AttributeSet attributeSet, int defStyle){
        super(context, attributeSet, defStyle);
        init(context);
    }

    //初始化容器
    public void init(Context context){
        setGravity(Gravity.CENTER);
        setOrientation(VERTICAL);
        setBackgroundColor(Color.WHITE);
    }

    //设置当前被选下按钮
    public void setInitChecked(int index){
        ((MyRadio)map.get(index)).setTouch(2);
        setCurrentValue(((MyRadio)map.get(index)).getText().toString());
    }

    public void setColumn(int column){
        this.column = column;
    }

    public void setCurrentValue(String value){
        this.currentValue = value;
    }

    public String getCurrentValue(){
        return this.currentValue;
    }

    public void setValues(List<String> values){
        this.values = values;
    }
    //初始化容器所有视图
    public void setView(final Context context){
        int size = values.size();
        int row = size/column;
        int leftSize = size%column;
        for(int i=0;i<row;i++){
            LinearLayout linearLayout = new LinearLayout(context);
            linearLayout.setOrientation(HORIZONTAL);
            linearLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 1));
            for(int j=0;j<column;j++){
                final MyRadio button = new MyRadio(context);
                button.setGravity(Gravity.CENTER);
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT,1);
                layoutParams.setMargins(8, 8, 8, 8);
                button.setLayoutParams(layoutParams);
                button.setText(values.get(column * i + j));
                currentIndex = column * i + j;
                button.setOnValueChangedListner(new MyRadio.OnValueChangedListner() {
                    @Override
                    public void OnValueChanged(String value) {
                        setCurrentValue(value);
                        clearSelected(currentIndex);
                    }
                });
                map.put(column * i + j,button);
                linearLayout.addView(button);
            }
            addView(linearLayout);
        }
        if(leftSize != 0){
            LinearLayout linearLayout = new LinearLayout(context);
            linearLayout.setOrientation(HORIZONTAL);
            linearLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 1));
            for(int m=0;m<column;m++){
                if(m<leftSize) {
                    final MyRadio button = new MyRadio(context);
                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1);
                    layoutParams.setMargins(8, 8, 8, 8);
                    button.setGravity(Gravity.CENTER);
                    button.setLayoutParams(layoutParams);
                    button.setText(values.get(size - leftSize + m));
                    currentIndex = size - leftSize + m;
                    button.setOnValueChangedListner(new MyRadio.OnValueChangedListner() {
                        @Override
                        public void OnValueChanged(String value) {
                            setCurrentValue(value);
                            clearSelected(currentIndex);
                        }
                    });
                    map.put(size - leftSize + m,button);
                    linearLayout.addView(button);
                }else {
                    LinearLayout.LayoutParams layoutParamsV = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1);
                    layoutParamsV.setMargins(8, 8, 8, 8);
                    Button view = new Button(context);
                    view.setLayoutParams(layoutParamsV);
                    view.setGravity(Gravity.CENTER);
                    view.setText("123");
                    view.setVisibility(INVISIBLE);
                    view.setBackgroundColor(Color.RED);
                    linearLayout.addView(view);
                }
            }
            addView(linearLayout);
        }
    }

    //清除所有选择
    private void clearSelected(int Index){
        System.out.println("length = "+map.size());
        for(int index = 0;index < map.size(); index ++){

            ((MyRadio)map.get(index)).setTouch(1);
        }
    }

}


容器继承自LinearLayout,里面自定义的LinearLayout,将控件按权重排列,按钮实现OnValueChangedListener,将其值回调。

第三部分:背景(贴上去,充充字数吧,另一个实现也是一样的,不贴了)

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:radius="3dp"></corners>
    <solid android:color="@color/lightblue"></solid>
    <stroke android:color="@color/lightblue" android:width="1dp"></stroke>
</shape>

最后,定义好了空间,自然就是怎样去引用了,在Activity的布局xml中:

<cn.leungyong.app.ui.view.ChoiceGroup
      android:id="@+id/choiceGroup"
      android:background="@color/white"
      android:layout_width="match_parent"
      android:layout_height="wrap_content">
</cn.leungyong.app.ui.view.ChoiceGroup>

在java源码中实现:

List<String> list = new ArrayList<String>();
list.add("施工");
list.add("服务");
list.add("设计");
list.add("监理");
list.add("其他");


ChoiceGroup choiceGroup = (ChoiceGroup)findViewById(R.id.choiceGroup)
choiceGroup.setColumn(3);//设置列数
choiceGroup.setValues(list);//设置记录列表
choiceGroup.setView(this);//设置视图
choiceGroup.setInitChecked(0);//设置最初默认被选按钮


choiceGroup.getCurrentValue();//获取当前被选择的按钮值

最后结果:





  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值