三种自定义圆形按钮的方法

占坑

1、自定义的view,在onDraw方法里用canvas绘制一个圆。

2、用ImageButton,然后背景传入一个圆形的图片。

3、用shape编写形状,button里指定shape。

 

只有方法3能有点击的阴影效果,方法1和2看不出点击效果

 

一:自定义view

画了圆之外,其实整个控件还是矩形的,必须让背景透明

public class CircleView extends Button {

    int mColor = Color.GRAY;

    Paint paint;

    private void init(){

        paint = new Paint();
        paint.setColor(mColor);

    }

    public CircleView(Context context) {
        super(context);
        init();

    }

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

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

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        int width = getWidth();
        int height = getHeight();
        int radius = Math.min(width,height)/2;
        canvas.drawCircle(width/2,height/2,radius,paint);

    }



}

 

二:放入圆形的背景图即可,这里不展开说了

 

三:编写shape文件

<?xml version="1.0" encoding="utf-8"?>

<shape

    xmlns:android= "http://schemas.android.com/apk/res/android"

    android:shape= "oval"椭圆

    android:useLevel= "false" >

    <solid android:color= "#CC0000" />颜色



    <size android:width= "20dp"

        android:height= "20dp" />

</shape>

 

整个布局文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.administrator.circletest.MainActivity">

    <com.example.administrator.circletest.CircleView
        android:background="#00000000"透明
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:id="@+id/view" />

    


    <ImageButton
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:background="@drawable/back"
        android:id="@+id/imageButton"
        android:layout_alignTop="@+id/view"
        android:layout_centerHorizontal="true" />


    <Button
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:background="@drawable/circle"
        android:layout_alignTop="@+id/imageButton"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

</RelativeLayout>

 

 

posted @ 2016-11-29 22:12  wzb的QQ空间  阅读(1239)  评论(0编辑  收藏  举报