Java、Kotlin代码实现自定义底部导航栏View

我们以纯代码的形式完成一个自定义view,只想要代码的请滑动到最下方,不多说,先上效果图,类似效果再往下看。

首先继承RelativeLayout,并实现需要实现的方法。我们需要手动画一个底部出来,所以我们可以在init方法中初始化一些东西

package com.goldze.mvvmhabit.app;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.RelativeLayout;


/**
 * 费浩东
 * 2019/1/4
 * Created by fhd
 */
public class MainBottomBarTest extends RelativeLayout{

    //全局画笔
    private Paint mPaint;

    public MainBottomBarTest(Context context) {
        super(context);
    }

    public MainBottomBarTest(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    private void init(Context context) {
        //初始化画笔
        mPaint = new Paint();

        //设置背景色为透明 如果我们不设置的话,会造成onDraw方法不执行
        setBackgroundColor(Color.TRANSPARENT);
    }

}

初始化工作做好后,我们利用画笔去画我们的底部凸起

    //矩形上移距离
    private Float mGroupTop = 40.f;

    //Bar底部颜色
    private Integer mBarColor = Color.WHITE;

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //设置画笔颜色
        mPaint.setColor(mBarColor);
        //画一个矩形,宽为父布局的宽度,高为父布局的高度减去mGroupTop
        canvas.drawRect(0, mGroupTop, getWidth(), getHeight(), mPaint);
        //画一个圆,x轴距离为父布局宽的一半,y轴为控件的半径
        canvas.drawCircle(getWidth() / 2, mRadius, mRadius, mPaint);
    }

在主布局中依赖我们的自定义View,看下图效果可以看到我们已经完成了底部+凸起的显示了

        <com.goldze.mvvmhabit.app.MainBottomBarTest
            android:layout_marginTop="80dp"
            android:id="@+id/bottomBar2Test"
            android:layout_width="match_parent"
            android:layout_height="80dp"/>

接着,用代码创建我们想要的控件,一共6个控件,实现思路是一个RadioGroup内部横向装5个按钮,我们继续在init方法中定义initView方法,我们将RadioGroup的方向设置为横向布局,具体在代码中有详细的注释。

可以看到我们只有4个Button,因为我们中间的图片想做成不同大小不同高低,所以我把它抽出来了,用其他方式实现,而布局问题使用了一个空的控件占位。


    //底部按钮
    private RadioButton radioOne;
    private RadioButton radioTwo;
    private RadioButton radioThree;
    private RadioButton radioFour;
    private RelativeLayout radioCenter;

    private void initView(Context context) {
        RadioGroup radioGroup = new RadioGroup(context);
        radioGroup.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        //设置框架内间距为底部矩形的差值
        radioGroup.setPadding(0, mGroupTop.intValue(), 0, 0);
        //设置布局内的对齐方式
        radioGroup.setGravity(Gravity.CENTER_VERTICAL);
        //设置RadioGroup子布局排列方向
        radioGroup.setOrientation(LinearLayout.HORIZONTAL);

        //创建第一个按钮实例
        radioOne = new RadioButton(context);
        //设置布局参数
        radioOne.setLayoutParams(new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f));
        //设置对齐方式
        radioOne.setGravity(Gravity.CENTER_HORIZONTAL);
        //设置RadioButton默认样式为空
        radioOne.setButtonDrawable(null);
        //设置文字
        radioOne.setText("kotlin1");
        //设置文字大小
        radioOne.setTextSize(10);

        //创建第二个按钮实例...
        radioTwo = new RadioButton(context);
        radioTwo.setGravity(Gravity.CENTER_HORIZONTAL);
        radioTwo.setLayoutParams(new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f));
        radioTwo.setButtonDrawable(null);
        radioTwo.setText("kotlin2");
        radioTwo.setTextSize(10);

        //创建中心按钮实例...
        radioCenter = new RelativeLayout(context);
        radioCenter.setLayoutParams(new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f));
        radioCenter.setGravity(Gravity.CENTER_HORIZONTAL);

        //创建第四个按钮实例...
        radioThree = new RadioButton(context);
        radioThree.setGravity(Gravity.CENTER_HORIZONTAL);
        radioThree.setLayoutParams(new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f));
        radioThree.setButtonDrawable(null);
        radioThree.setText("kotlin3");
        radioThree.setTextSize(10);

        //创建第五个按钮实例...
        radioFour = new RadioButton(context);
        radioFour.setGravity(Gravity.CENTER_HORIZONTAL);
        radioFour.setLayoutParams(new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f));
        radioFour.setButtonDrawable(null);
        radioFour.setText("kotlin4");
        radioFour.setTextSize(10);

        //为RadioGroup添加子View
        radioGroup.addView(radioOne);
        radioGroup.addView(radioTwo);
        radioGroup.addView(radioCenter);
        radioGroup.addView(radioThree);
        radioGroup.addView(radioFour);
        //最后添加RadioGroup
        addView(radioGroup);
    }

然后,我们给控件设置默认的图片,请自行替换下列代码内的图片

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@mipmap/main_navigation_bar_my" android:state_checked="false"/>
    <item android:drawable="@mipmap/main_navigation_bar_my_checked" android:state_checked="true"/>
</selector>
    //默认的资源文件
    private int[] defRes = {R.drawable.layout_bottom_bar_select, R.drawable.layout_bottom_bar_select,
            R.drawable.layout_bottom_bar_select, R.drawable.layout_bottom_bar_select};

    //设置资源图片
    public void setResourcePictures(int[] drawableTop) {
        if (drawableTop.length != 4) {
            Log.e("setResourcePictures", "MainBottomBar中所提供的图片资源必须为4个: ");
            return;
        }
        radioOne.setCompoundDrawablesRelativeWithIntrinsicBounds(null, this.getResources().getDrawable(drawableTop[0]), null, null);
        radioTwo.setCompoundDrawablesRelativeWithIntrinsicBounds(null, this.getResources().getDrawable(drawableTop[1]), null, null);
        radioThree.setCompoundDrawablesRelativeWithIntrinsicBounds(null, this.getResources().getDrawable(drawableTop[2]), null, null);
        radioFour.setCompoundDrawablesRelativeWithIntrinsicBounds(null, this.getResources().getDrawable(drawableTop[3]), null, null);
    }

看看现在的效果,已经大致出效果了,控件有点高,我们可以在主布局文件中设置他的高度,我们把它调至65.

        <com.goldze.mvvmhabit.app.MainBottomBarTest
            android:layout_marginTop="80dp"
            android:id="@+id/bottomBar2Test"
            android:layout_width="match_parent"
            android:layout_height="65dp"/>

好了,高度差不多了,如果你想再低,可以继续通过外部布局调整到你想要的效果。很明显接下来我们需要显示中间的按钮。我这里一开始是在外部继续创建一个ImageView可是后来定位一直有问题,我就采取了draw的方式来实现中心按钮的问题。在ondraw方法中加入下列代码

    //中心的Bitmap
    private Bitmap mBitmap ;

    //中心图片上面移动距离  默认中心点
    private Float mCenterBottom = 0.f;

    //中心图片,可以不需要在内部实现,可以再外部再次调用更改图片
    private int centerImage = R.mipmap.ic_launcher ;

    //初始化bitmap图片
    mBitmap = BitmapFactory.decodeResource(getResources(), centerImage);
    //裁剪图片置为统一大小
    mBitmap = zoomImage(mBitmap,150,150,true);

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //设置画笔颜色
        //...
        //画一个矩形....
        //...
        //画一个圆....
        //...
        canvas.drawBitmap(mBitmap, getWidth() / 2 - mBitmap.getWidth() / 2, getHeight() / 2 - mBitmap.getHeight() / 2 + mCenterBottom, mPaint);
    }

考虑到图片大小不一致,可能导致过大情况出现,我们加入裁剪图片大小的方法。并设置开关,支持外部设置图片大小

public static Bitmap zoomImage(Bitmap bgimage, double newWidth, double newHeight ,boolean fixed) {
        // 获取这个图片的宽和高
        float width = bgimage.getWidth();
        float height = bgimage.getHeight();
        // 创建操作图片用的matrix对象
        Matrix matrix = new Matrix();
        // 计算宽高缩放率
        float scaleWidth =  width / width;
        float scaleHeight = height / height;
        if (fixed){
            if ( newWidth < width) {
                scaleWidth = ((float) newWidth) / width;
            }
            if (newHeight < height) {
                scaleHeight = ((float) newHeight) / height;
            }
        } else {
            scaleWidth = ((float) newWidth) / width;
            scaleHeight = ((float) newHeight) / height;
        }
        // 缩放图片动作
        matrix.postScale(scaleWidth, scaleHeight);
        return Bitmap.createBitmap(bgimage, 0, 0, (int) width, (int) height, matrix, true);
    }

至此我们的效果已经出来了,再就是回调等事件了,我之前博客已经写过实现方式了,我就不重复叙述了。如果需要可点击前往

接下来贴出完整的代码。如果对您有帮助,请点赞关注一下哦~谢谢,代码有两段哦,先Java后Kotlin

package com.goldze.mvvmhabit.app;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;

import com.goldze.mvvmhabit.R;

/**
 * 费浩东
 * 2019/1/4
 * Created by fhd
 */
public class MainBottomBar2Java extends RelativeLayout implements View.OnClickListener {

    //底部按钮
    private RadioButton radioOne;
    private RadioButton radioTwo;
    private RadioButton radioThree;
    private RadioButton radioFour;
    private RelativeLayout radioCenter;

    //默认的资源文件
    private int[] defRes = {R.drawable.layout_bottom_bar_select, R.drawable.layout_bottom_bar_select,
            R.drawable.layout_bottom_bar_select, R.drawable.layout_bottom_bar_select};

    private int centerImage = R.mipmap.ic_launcher ;

    //中心的Bitmap
    private Bitmap mBitmap ;

    //圆半径
    private Float mRadius = 80.f;

    //全局画笔
    private Paint mPaint;

    //矩形上移距离
    private Float mGroupTop = 40.f;

    //中心图片上面移动距离  默认中心点
    private Float mCenterBottom = 0.f;

    //Bar底部颜色
    private Integer mBarColor = Color.WHITE;

    //点击回调
    private onRadioClickListener mListener;

    //避免重复点击 默认打开
    private Boolean mRepeated = true;

    //第一个按钮为默认按钮 记录当前选中按钮
    private Integer mDefaultPage = 0;

    public MainBottomBar2Java(Context context) {
        super(context);
    }

    public MainBottomBar2Java(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public MainBottomBar2Java(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //设置画笔颜色
        mPaint.setColor(mBarColor);
        //画一个矩形,宽为父布局的宽度,高为父布局的高度减去mGroupTop
        canvas.drawRect(0, mGroupTop, getWidth(), getHeight(), mPaint);
        //画一个圆,x轴距离为父布局宽的一半,y轴为控件的半径
        canvas.drawCircle(getWidth() / 2, mRadius, mRadius, mPaint);

        canvas.drawBitmap(mBitmap, getWidth() / 2 - mBitmap.getWidth() / 2, getHeight() / 2 - mBitmap.getHeight() / 2 + mCenterBottom, mPaint);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    //设置资源图片
    public void setResourcePictures(int[] drawableTop) {
        if (drawableTop.length != 4) {
            Log.e("setResourcePictures", "MainBottomBar中所提供的图片资源必须为4个: ");
            return;
        }
        radioOne.setCompoundDrawablesRelativeWithIntrinsicBounds(null, this.getResources().getDrawable(drawableTop[0]), null, null);
        radioTwo.setCompoundDrawablesRelativeWithIntrinsicBounds(null, this.getResources().getDrawable(drawableTop[1]), null, null);
        radioThree.setCompoundDrawablesRelativeWithIntrinsicBounds(null, this.getResources().getDrawable(drawableTop[2]), null, null);
        radioFour.setCompoundDrawablesRelativeWithIntrinsicBounds(null, this.getResources().getDrawable(drawableTop[3]), null, null);
    }

    //设置中心图片
    public void setCenterImage(int centerImage){
        this.centerImage = centerImage ;
        mBitmap = BitmapFactory.decodeResource(getResources(), centerImage);
//        mBitmap = mBitmap.copy(Bitmap.Config.ALPHA_8,true);
        mBitmap = zoomImage(mBitmap,150,150,true);
        invalidate();
    }

    //设置中心图片
    public void setCenterImage(int centerImage,int newWidth,int newHeight){
        this.centerImage = centerImage ;
        mBitmap = BitmapFactory.decodeResource(getResources(), centerImage);
        mBitmap = zoomImage(mBitmap,newWidth,newHeight,false);
        invalidate();
    }

    public static Bitmap zoomImage(Bitmap bgimage, double newWidth, double newHeight ,boolean fixed) {
        // 获取这个图片的宽和高
        float width = bgimage.getWidth();
        float height = bgimage.getHeight();
        // 创建操作图片用的matrix对象
        Matrix matrix = new Matrix();
        // 计算宽高缩放率
        float scaleWidth =  width / width;
        float scaleHeight = height / height;
        if (fixed){
            if ( newWidth < width) {
                scaleWidth = ((float) newWidth) / width;
            }
            if (newHeight < height) {
                scaleHeight = ((float) newHeight) / height;
            }
        } else {
            scaleWidth = ((float) newWidth) / width;
            scaleHeight = ((float) newHeight) / height;
        }
        // 缩放图片动作
        matrix.postScale(scaleWidth, scaleHeight);
        return Bitmap.createBitmap(bgimage, 0, 0, (int) width, (int) height, matrix, true);
    }

    public void setRadioText(String[] strings) {
        Log.e("setRadioText", "s: " + strings.length);
        if (strings.length != 4) {
            return;
        }
        radioOne.setText(strings[0]);
        radioTwo.setText(strings[1]);
        radioThree.setText(strings[2]);
        radioFour.setText(strings[3]);
    }

    private void init(Context context) {
        //初始化画笔
        mPaint = new Paint();
        //初始化bitmap图片
        mBitmap = BitmapFactory.decodeResource(getResources(), centerImage);
        //裁剪图片置为统一大小
        mBitmap = zoomImage(mBitmap,150,150,true);
        //设置背景色为透明 如果我们不设置的话,会造成onDraw方法不执行
        setBackgroundColor(Color.TRANSPARENT);
        setGravity(CENTER_HORIZONTAL);
        //初始化控件
        initView(context);
        //初始化点击
        initListener();
    }

    private void initView(Context context) {
        RadioGroup radioGroup = new RadioGroup(context);
        radioGroup.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        radioGroup.setPadding(0, mGroupTop.intValue(), 0, 0);
        radioGroup.setGravity(Gravity.CENTER_VERTICAL);
        radioGroup.setOrientation(LinearLayout.HORIZONTAL);

        //创建第一个按钮实例
        radioOne = new RadioButton(context);
        //设置布局参数
        radioOne.setLayoutParams(new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f));
        //设置对齐方式
        radioOne.setGravity(Gravity.CENTER_HORIZONTAL);
        //设置RadioButton默认样式为空
        radioOne.setButtonDrawable(null);
        //设置文字
        radioOne.setText("kotlin1");
        //设置文字大小
        radioOne.setTextSize(10);

        //创建第二个按钮实例...
        radioTwo = new RadioButton(context);
        radioTwo.setGravity(Gravity.CENTER_HORIZONTAL);
        radioTwo.setLayoutParams(new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f));
        radioTwo.setButtonDrawable(null);
        radioTwo.setText("kotlin2");
        radioTwo.setTextSize(10);

        //创建中心按钮实例...
        radioCenter = new RelativeLayout(context);
        radioCenter.setLayoutParams(new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f));
        radioCenter.setGravity(Gravity.CENTER_HORIZONTAL);

        //创建第四个按钮实例...
        radioThree = new RadioButton(context);
        radioThree.setGravity(Gravity.CENTER_HORIZONTAL);
        radioThree.setLayoutParams(new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f));
        radioThree.setButtonDrawable(null);
        radioThree.setText("kotlin3");
        radioThree.setTextSize(10);

        //创建第五个按钮实例...
        radioFour = new RadioButton(context);
        radioFour.setGravity(Gravity.CENTER_HORIZONTAL);
        radioFour.setLayoutParams(new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f));
        radioFour.setButtonDrawable(null);
        radioFour.setText("kotlin4");
        radioFour.setTextSize(10);

        //设置资源文件
        setResourcePictures(defRes);
        //设置默认按钮
        setDefaultPage();


        //为RadioGroup添加子View
        radioGroup.addView(radioOne);
        radioGroup.addView(radioTwo);
        radioGroup.addView(radioCenter);
        radioGroup.addView(radioThree);
        radioGroup.addView(radioFour);
        //最后添加RadioGroup
        addView(radioGroup);
    }

    private void initListener() {
        //设置点击方法
        radioOne.setOnClickListener(this);
        radioTwo.setOnClickListener(this);
        radioThree.setOnClickListener(this);
        radioFour.setOnClickListener(this);
        radioCenter.setOnClickListener(this);
    }

    //内部使用,默认使用的页面
    private void setDefaultPage() {
        setDefaultPage(mDefaultPage);
    }

    //设置默认打开的按钮
    public void setDefaultPage(Integer page) {
        //重置当前page
        mDefaultPage = page;
        switch (page) {
            case 0:
                radioOne.setChecked(true);
                break;
            case 1:
                radioTwo.setChecked(true);
                break;
            case 2:
                break;
            case 3:
                radioThree.setChecked(true);
                break;
            case 4:
                radioFour.setChecked(true);
                break;
        }
    }

    @Override
    public void onClick(View v) {
        if (v == radioOne) {
            clickInterception(0);
            radioTwo.setChecked(false);
            radioThree.setChecked(false);
            radioFour.setChecked(false);
        } else if (v == radioTwo) {
            clickInterception(1);
            radioOne.setChecked(false);
            radioThree.setChecked(false);
            radioFour.setChecked(false);
        } else if (v == radioCenter) {
            radioOne.setChecked(false);
            radioTwo.setChecked(false);
            radioThree.setChecked(false);
            radioFour.setChecked(false);
            clickInterception(2);
        } else if (v == radioThree) {
            clickInterception(3);
            radioOne.setChecked(false);
            radioTwo.setChecked(false);
            radioFour.setChecked(false);
        } else if (v == radioFour) {
            clickInterception(4);
            radioOne.setChecked(false);
            radioTwo.setChecked(false);
            radioThree.setChecked(false);
        }
    }

    //设置点击回调
    public void setOnRadioClickListener(onRadioClickListener onRadioClickListener) {
        mListener = onRadioClickListener;
    }

    //按钮点击回调
    public interface onRadioClickListener {
        void onClick(int postion);
    }

    //点击拦截,过滤重复点击
    private void clickInterception(int page) {
        //重复过滤开启并且点击记录重复视为重复点击
        if (mRepeated && page == mDefaultPage) {
            return;
        }
        //记录新的页码.
        mDefaultPage = page;
        //开始回调
        mListener.onClick(page);
    }

}
package com.goldze.mvvmhabit.app

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Matrix
import android.graphics.Paint
import android.util.AttributeSet
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.RelativeLayout

import com.goldze.mvvmhabit.R

/**
 * 费浩东
 * 2019/1/4
 * Created by fhd
 */
class MainBottomBar2Kt : RelativeLayout, View.OnClickListener {

    //底部按钮
    private var radioOne: RadioButton? = null
    private var radioTwo: RadioButton? = null
    private var radioThree: RadioButton? = null
    private var radioFour: RadioButton? = null
    private var radioCenter: RelativeLayout? = null

    //默认的资源文件
    private val defRes = intArrayOf(R.drawable.layout_bottom_bar_select, R.drawable.layout_bottom_bar_select, R.drawable.layout_bottom_bar_select, R.drawable.layout_bottom_bar_select)

    private var centerImage = R.mipmap.ic_launcher
    private var mBitmap: Bitmap? = null

    //圆半径
    private val mRadius = 80f

    //全局画笔
    private var mPaint: Paint? = null

    //矩形上移距离
    private val mGroupTop = 40f

    //中心图片上面移动距离  默认中心点
    private val mCenterBottom = 0f

    //Bar底部颜色
    private val mBarColor = Color.WHITE

    //点击回调
    private var mListener: onRadioClickListener? = null

    //避免重复点击 默认打开
    private val mRepeated = true

    //第一个按钮为默认按钮 记录当前选中按钮
    private var mDefaultPage: Int? = 0

    constructor(context: Context) : super(context) {}

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        init(context)
    }

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {}

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        mPaint!!.color = mBarColor
        canvas.drawRect(0f, mGroupTop, width.toFloat(), height.toFloat(), mPaint!!)
        canvas.drawCircle((width / 2).toFloat(), mRadius, mRadius, mPaint!!)

        canvas.drawBitmap(mBitmap!!, (width / 2 - mBitmap!!.width / 2).toFloat(), height / 2 - mBitmap!!.height / 2 + mCenterBottom, mPaint)
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    }

    //设置资源图片
    fun setResourcePictures(drawableTop: IntArray) {
        if (drawableTop.size != 4) {
            Log.e("setResourcePictures", "MainBottomBar中所提供的图片资源必须为4个: ")
            return
        }
        radioOne!!.setCompoundDrawablesRelativeWithIntrinsicBounds(null, this.resources.getDrawable(drawableTop[0]), null, null)
        radioTwo!!.setCompoundDrawablesRelativeWithIntrinsicBounds(null, this.resources.getDrawable(drawableTop[1]), null, null)
        radioThree!!.setCompoundDrawablesRelativeWithIntrinsicBounds(null, this.resources.getDrawable(drawableTop[2]), null, null)
        radioFour!!.setCompoundDrawablesRelativeWithIntrinsicBounds(null, this.resources.getDrawable(drawableTop[3]), null, null)
    }

    //设置中心图片
    fun setCenterImage(centerImage: Int) {
        this.centerImage = centerImage
        mBitmap = BitmapFactory.decodeResource(resources, centerImage)
        //        mBitmap = mBitmap.copy(Bitmap.Config.ALPHA_8,true);
        mBitmap = zoomImage(mBitmap!!, 150.0, 150.0, true)
        invalidate()
    }

    //设置中心图片
    fun setCenterImage(centerImage: Int, newWidth: Int, newHeight: Int) {
        this.centerImage = centerImage
        mBitmap = BitmapFactory.decodeResource(resources, centerImage)
        mBitmap = zoomImage(mBitmap!!, newWidth.toDouble(), newHeight.toDouble(), false)
        invalidate()
    }

    fun setRadioText(strings: Array<String>) {
        Log.e("setRadioText", "s: " + strings.size)
        if (strings.size != 4) {
            return
        }
        radioOne!!.text = strings[0]
        radioTwo!!.text = strings[1]
        radioThree!!.text = strings[2]
        radioFour!!.text = strings[3]
    }

    private fun init(context: Context) {
        mPaint = Paint()
        mBitmap = BitmapFactory.decodeResource(resources, centerImage)
        mBitmap = zoomImage(mBitmap!!, 150.0, 150.0, true)
        setBackgroundColor(Color.TRANSPARENT)
        gravity = RelativeLayout.CENTER_HORIZONTAL
        val radioGroup = RadioGroup(context)
        radioGroup.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
        radioGroup.setPadding(0, mGroupTop.toInt(), 0, 0)
        radioGroup.gravity = Gravity.CENTER_VERTICAL
        radioGroup.orientation = LinearLayout.HORIZONTAL

        //创建第一个按钮实例
        radioOne = RadioButton(context)
        //设置布局参数
        radioOne!!.layoutParams = LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f)
        //设置对齐方式
        radioOne!!.gravity = Gravity.CENTER_HORIZONTAL
        //设置RadioButton默认样式为空
        radioOne!!.buttonDrawable = null
        //设置文字
        radioOne!!.text = "kotlin1"
        //设置文字大小
        radioOne!!.textSize = 10f

        //创建第二个按钮实例...
        radioTwo = RadioButton(context)
        radioTwo!!.gravity = Gravity.CENTER_HORIZONTAL
        radioTwo!!.layoutParams = LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f)
        radioTwo!!.buttonDrawable = null
        radioTwo!!.text = "kotlin2"
        radioTwo!!.textSize = 10f

        //创建中心按钮实例...
        radioCenter = RelativeLayout(context)
        radioCenter!!.layoutParams = LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f)
        radioCenter!!.gravity = Gravity.CENTER_HORIZONTAL

        //创建第四个按钮实例...
        radioThree = RadioButton(context)
        radioThree!!.gravity = Gravity.CENTER_HORIZONTAL
        radioThree!!.layoutParams = LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f)
        radioThree!!.buttonDrawable = null
        radioThree!!.text = "kotlin3"
        radioThree!!.textSize = 10f

        //创建第五个按钮实例...
        radioFour = RadioButton(context)
        radioFour!!.gravity = Gravity.CENTER_HORIZONTAL
        radioFour!!.layoutParams = LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f)
        radioFour!!.buttonDrawable = null
        radioFour!!.text = "kotlin4"
        radioFour!!.textSize = 10f

        //设置资源文件
        setResourcePictures(defRes)
        //设置默认按钮
        setDefaultPage()

        //设置点击方法
        radioOne!!.setOnClickListener(this)
        radioTwo!!.setOnClickListener(this)
        radioThree!!.setOnClickListener(this)
        radioFour!!.setOnClickListener(this)
        radioCenter!!.setOnClickListener(this)

        //为RadioGroup添加子View
        radioGroup.addView(radioOne)
        radioGroup.addView(radioTwo)
        radioGroup.addView(radioCenter)
        radioGroup.addView(radioThree)
        radioGroup.addView(radioFour)
        //最后添加RadioGroup
        addView(radioGroup)
    }

    //内部使用,默认使用的页面
    private fun setDefaultPage() {
        setDefaultPage(mDefaultPage)
    }

    //设置默认打开的按钮
    fun setDefaultPage(page: Int?) {
        //重置当前page
        mDefaultPage = page
        when (page) {
            0 -> radioOne!!.isChecked = true
            1 -> radioTwo!!.isChecked = true
            2 -> { }
            3 -> radioThree!!.isChecked = true
            4 -> radioFour!!.isChecked = true
        }
    }

    override fun onClick(v: View) {
        if (v === radioOne) {
            clickInterception(0)
            radioTwo!!.isChecked = false
            radioThree!!.isChecked = false
            radioFour!!.isChecked = false
        } else if (v === radioTwo) {
            clickInterception(1)
            radioOne!!.isChecked = false
            radioThree!!.isChecked = false
            radioFour!!.isChecked = false
        } else if (v === radioCenter) {
            radioOne!!.isChecked = false
            radioTwo!!.isChecked = false
            radioThree!!.isChecked = false
            radioFour!!.isChecked = false
            clickInterception(2)
        } else if (v === radioThree) {
            clickInterception(3)
            radioOne!!.isChecked = false
            radioTwo!!.isChecked = false
            radioFour!!.isChecked = false
        } else if (v === radioFour) {
            clickInterception(4)
            radioOne!!.isChecked = false
            radioTwo!!.isChecked = false
            radioThree!!.isChecked = false
        }
    }

    //设置点击回调
    fun setOnRadioClickListener(onRadioClickListener: onRadioClickListener) {
        mListener = onRadioClickListener
    }

    //按钮点击回调
    interface onRadioClickListener {
        fun onClick(postion: Int)
    }

    //点击拦截,过滤重复点击
    private fun clickInterception(page: Int) {
        //重复过滤开启并且点击记录重复视为重复点击
        if (mRepeated && page == mDefaultPage) {
            return
        }
        //记录新的页码.
        mDefaultPage = page
        //开始回调
        mListener!!.onClick(page)
    }

    companion object {
        fun zoomImage(bgimage: Bitmap, newWidth: Double, newHeight: Double, fixed: Boolean): Bitmap {
            // 获取这个图片的宽和高
            val width = bgimage.width.toFloat()
            val height = bgimage.height.toFloat()
            // 创建操作图片用的matrix对象
            val matrix = Matrix()
            // 计算宽高缩放率
            var scaleWidth = width / width
            var scaleHeight = height / height
            if (fixed) {
                if (newWidth < width) {
                    scaleWidth = newWidth.toFloat() / width
                }
                if (newHeight < height) {
                    scaleHeight = newHeight.toFloat() / height
                }
            } else {
                scaleWidth = newWidth.toFloat() / width
                scaleHeight = newHeight.toFloat() / height
            }
            // 缩放图片动作
            matrix.postScale(scaleWidth, scaleHeight)
            return Bitmap.createBitmap(bgimage, 0, 0, width.toInt(), height.toInt(), matrix, true)
        }
    }

}

猜你喜欢

转载自blog.csdn.net/LikeBoke/article/details/86088067