Android 自定义Radiobutton样式

分类:Android     发布:2020-01-05     来源:本站     浏览:349 次
Android中的Radiobutton可以设置横向和竖向排列选择项,但是无法做到自适应宽度。
比如:实现这样的效果:

在网上找到了比较好的一种方式。
1.自定义RadioGroup控件
package com.rc.news.control;


import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import java.util.ArrayList;
import java.util.List;
public class CustomRadioGroup extends RadioGroup {

    private List<RowView> rowViews;//存放每行radioBotton的集合
    private int horizontalSpacing = 20;//默认水平间距
    private int verticalSpacing = 10;//默认垂直间距
    private Context context;
    private OnclickListener listener;

    public void setListener(OnclickListener listener) {
        this.listener = listener;
    }

    public CustomRadioGroup(Context context) {
        this(context, null);
    }

    public CustomRadioGroup(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        rowViews = new ArrayList<>();
    }

    //设置水平间距(单位dp)
    public void setHorizontalSpacing(int horizontalSpacing_dp) {
        this.horizontalSpacing = dip2px(context, horizontalSpacing_dp);
    }

    //设置垂直间距(单位dp)
    public void setVerticalSpacing(int verticalSpacing_dp) {
        this.verticalSpacing = dip2px(context, verticalSpacing_dp);
    }

    public int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        rowViews.clear();//清空集合
        //获取屏幕总宽度(包含默认paddingleft和paddingright)
        int width = MeasureSpec.getSize(widthMeasureSpec);
        //去除默认宽带与实际宽带进行比较
        int nopaddingWidth = width - getPaddingLeft() - getPaddingRight();

        RowView rowView = null;
        //遍历所有的view进行分行
        for (int i = 0; i < getChildCount(); i++) {
            View childView = getChildAt(i);//获取对应的view
            childView.measure(0, 0);//通知父view进行测量
            if (rowView == null) {
                rowView = new RowView();
            }
            if (rowView.getRowViews().size() == 0) {//如果当前行一个view都没有,,直接添加,不用比较
                rowView.addChidView(childView);
            } else if (rowView.getRowWidth() + horizontalSpacing + childView.getMeasuredWidth() > nopaddingWidth) {
                //如果当前的行宽度+水平间距+当前view的宽带大于nopaddingWidth,则需要换行
                rowViews.add(rowView);//将之前的行保存起来
                rowView = new RowView();//重新创建一行,,将当前的view保存起来
                rowView.addChidView(childView);
            } else {
                rowView.addChidView(childView);//当前childView添加后没有超出nopaddingWidth,可以将childView添加到当前行
            }
            // 如果当前childView是最后一个子View,会造成最后一行line丢失
            if (i == getChildCount() - 1) {
                rowViews.add(rowView);
            }
        }
        //计算layout所有行需要的高度
        int heght = getPaddingTop() + getPaddingBottom();//加上padding值
        for (int i = 0; i < rowViews.size(); i++) {
            heght += rowViews.get(i).getRowHeight();//添加每行高度
        }
        heght += (rowViews.size() - 1) * verticalSpacing;//添加垂直间距高度
        setMeasuredDimension(width, heght);//向父view申请宽带和高度
        if (getChildCount() == 0) {
            setMeasuredDimension(0, 0);
        }
    }

    //将每个view放到对应的位置
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        int paddingLeft = getPaddingLeft();
        int paddingTop = getPaddingTop();

        for (int i = 0; i < rowViews.size(); i++) {
            RowView rowView = rowViews.get(i);//获取到当前的line对象
            //后面每一行的top值要相应的增加,当前行的top是上一行的top值+height+垂直间距
            if (i > 0) {
                paddingTop += rowViews.get(i - 1).getRowHeight() + verticalSpacing;
            }
            List<View> viewList = rowView.getRowViews();//获取line的子View集合

            for (int j = 0; j < viewList.size(); j++) {
                View childView = viewList.get(j);//获取当前的子View
                if (j == 0) {
                    //每行的第一个子View,需要靠左边摆放
                    childView.layout(paddingLeft, paddingTop, paddingLeft + childView.getMeasuredWidth(),
                            paddingTop + childView.getMeasuredHeight());
                } else {
                    //摆放后面的子View,需要参考前一个子View的right
                    View preView = viewList.get(j - 1);//获取前一个子View
                    int left = preView.getRight() + horizontalSpacing;//前一个VIew的right+水平间距
                    childView.layout(left, preView.getTop(), left + childView.getMeasuredWidth(), preView.getBottom());
                }
            }
        }
    }

    public interface OnclickListener {
        void OnText(String text);
    }

    class RowView {
        private List<View> lineViews;//用于存放每行的view
        private int rowWidth;//行宽
        private int rowHeight;//行高

        public RowView() {
            lineViews = new ArrayList<>();
        }

        public List<View> getRowViews() {
            return lineViews;
        }

        public int getRowWidth() {
            return rowWidth;
        }

        public int getRowHeight() {
            return rowHeight;
        }

        //存放view到rowViews
        public void addChidView(View view) {
            if (!lineViews.contains(view)) {
                ((RadioButton) view).setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (listener != null) {
                            listener.OnText(((RadioButton) v).getText().toString().trim());
                        }
                    }
                });
                //更新高度和宽度
                if (lineViews.size() == 0) {
                    //第一次添加view,不用添加水平间距
                    rowWidth = view.getMeasuredWidth();
                } else {
                    //不是第一次添加,需要添加水平间距
                    rowWidth += view.getMeasuredWidth() + horizontalSpacing;
                }
                //height应该是所有子view中高度最大的那个
                rowHeight = Math.max(view.getMeasuredHeight(), rowHeight);
                lineViews.add(view);
            }

        }

    }

}

2.contorl_custom_radiobutton.xml
<?xml version="1.0" encoding="utf-8"?>
<RadioButton xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checked="false"
    android:gravity="center"
    android:paddingLeft="5dp"
    android:paddingTop="2dp"
    android:paddingRight="5dp"
    android:paddingBottom="2dp"
    android:textColor="#000000"
    android:background="#ffffff"
    android:text="黑色"   >
</RadioButton>
3.使用方式
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    android:orientation="vertical"
    android:padding="10dp">

    <EditText
        android:id="@+id/txtContent"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:layout_marginBottom="10dp"
        android:background="@drawable/control_textarea_style"
        android:gravity="top"
        android:hint="写下这一刻的想法..."
        android:inputType="text|textMultiLine"
        android:padding="5dp"
        android:textColor="#000000"
        android:textSize="14dp"
        tools:ignore="MissingConstraints" />

    <!--分类-->
    <com.rc.news.control.CustomRadioGroup
        android:id="@+id/customRadioGroup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dip"
        android:orientation="horizontal"></com.rc.news.control.CustomRadioGroup>

    <Button
        android:id="@+id/btnSubmit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:background="@drawable/contorl_button_style"
        android:text="提 交"
        android:textColor="#ffffff"
        android:textSize="16dp" />


</LinearLayout>
后台代码
package com.rc.news.ui;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import android.app.Fragment;
import android.widget.RadioButton;
import android.widget.TextView;

import com.rc.news.R;
import com.rc.news.control.CustomRadioGroup;

public class NewsFragment extends Fragment {
    View view;
    TextView title;
    String[] str1 = new String[]{"新闻动态", "办事指南", "好人好事", "失物招领", "二手交易", "其他事项"};
    private void setSpacing(CustomRadioGroup cg, int widthdp, int heightdp) {
        cg.setHorizontalSpacing(widthdp);
        cg.setVerticalSpacing(heightdp);
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        
        view = inflater.inflate(R.layout.page_news, container, false);
        final CustomRadioGroup radioGroup = (CustomRadioGroup) view.findViewById(R.id.customRadioGroup);
        setSpacing(radioGroup, 12, 8);
        for (int i = 0; i < str1.length; i++) {
            RadioButton radioButton = (RadioButton) getLayoutInflater().inflate(R.layout.contorl_custom_radiobutton, null);
            radioButton.setText(str1[i]);
            radioGroup.addView(radioButton);
        }
        radioGroup.setListener(new CustomRadioGroup.OnclickListener() {
            @Override
            public void OnText(String text) {
            }
        });

        final Context activity = container.getContext();
        return view;
    }

}


如果觉得文章对您有帮助,您可以对我进行打赏 ¥1.12 元(金额随机^_^,每次刷新金额不同)。

请使用支付宝扫码支付

留言评论

*称  呼:
*联系方式: 方便与您取得联系,推荐使用邮箱。
*内  容:

已有评论

暂无数据

上一篇:流动人员人事档案基础信息采集规范

下一篇:Canvas 画贝塞尔曲线(二阶曲线和三阶曲线)