Android自定义控件之翻转按钮

先看一下效果


20180515_153605.gif

一.先定义控件的基本结构

这里我们定义一个容器,所以是在ViewGroup的基础上扩展。
简单起见,直接使用扩展自ViewGroup的LinearLayout,并将我们的控件扩展自LinearLayout。

1.按钮的基本布局如下
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <FrameLayout
        android:id="@+id/mButton"
        android:background="@color/colorPrimary"
        android:padding="5dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:id="@+id/buttonText"
            android:text="FLIPPED BUTTON"
            android:textColor="@android:color/white"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </FrameLayout>
</LinearLayout>
2.自定义控件开门三步走

构造函数,onMeasure,onLayout

package net.codepig.customviewdemo.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;

import net.codepig.customviewdemo.R;

public class flippedButton extends LinearLayout {
    private Context mContext;
    private int mWidth;//容器的宽度
    private int mHeight;//容器的高度
    private TextView buttonText;
    private FrameLayout mButton;
    public flippedButton(Context context){
        super(context);
        this.mContext = context;
        init(context);
    }

    public flippedButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        init(context);
    }

    public flippedButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        init(context);
    }

    private void init(Context context){
        //使用xml中的布局
        LayoutInflater.from(context).inflate(R.layout.filpped_button,this, true);
        mButton=findViewById(R.id.mButton);
        buttonText=findViewById(R.id.buttonText);
    }

    //测量子View
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        measureChildren(widthMeasureSpec, heightMeasureSpec);
        mWidth = getMeasuredWidth();
        mHeight = getMeasuredHeight();

        //遍历子元件
//        int childCount = this.getChildCount();
//        for (int i = 0; i < childCount; i++) {
//            View child = this.getChildAt(i);
//            this.measureChild(child, widthMeasureSpec, heightMeasureSpec);
//            int cw = child.getMeasuredWidth();
//            int ch = child.getMeasuredHeight();
//        }
    }

    //排列子View的位置
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int childTop = 0;
        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            if (child.getVisibility() != GONE) {
                child.layout(0, childTop,child.getMeasuredWidth(), childTop + child.getMeasuredHeight());
                childTop = childTop + child.getMeasuredHeight();
            }
        }
    }
}
3.在Activity的布局中直接使用
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:orientation="vertical">
    <net.codepig.customviewdemo.view.flippedButton
        android:id="@+id/flippedButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </net.codepig.customviewdemo.view.flippedButton>
</LinearLayout>

现在可以看到一个最基本的自定义控件已经可以使用了。

二.接下来是重点,控件真正“自定义”的部分。

1.添加自定义事件

a.先定义自定义事件接口

/**
     * 定义接口
     */
    public interface IMyClick{
        public void onMyClick(String str);
    }

    /**
     * 初始化接口变量
     */
    IMyClick iMyClick=null;

    /**
     * 自定义事件监听
     * @param _iMyClick
     */
    public void setOnMyClickListener(IMyClick _iMyClick){
        iMyClick=_iMyClick;
    }

b.添加按钮点击事件的监听并调用接口传参

mButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                iMyClick.onMyClick("clicked me");
                flipMe();
            }
        });

c.父级Activity监听事件

fButton=(flippedButton) findViewById(R.id.flippedButton);
        fButton.setOnMyClickListener(new flippedButton.IMyClick(){
            @Override
            public void onMyClick(String str) {
                Log.d(LOG_TAG,str);
            }
        });
2.绘制按钮翻转的动画

这里的3d变换需要用到Camera(android.graphics.Camera)、Matrix。
这里可以想象成用Camera拍摄原件的图形,并将拍摄得到的bitmap传入matrix再绘制到Canvas。
而改变Camera镜头角度就可以得到缩放变形后的图像以实现3d效果。
参考官方demo里的这个工具类的范例Rotate3dAnimation.java(其实是照搬)

a.先建一个3d变换的工具类:

package net.codepig.customviewdemo.model;

import android.graphics.Camera;//注意使用的是graphics里的而不是hardware里的
import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.graphics.Matrix;

/**
 * An animation that rotates the view on the Y axis between two specified angles.
 * This animation also adds a translation on the Z axis (depth) to improve the effect.
 */
public class Rotate3dAnimation extends Animation {
    private final float mFromDegrees;
    private final float mToDegrees;
    private final float mCenterX;
    private final float mCenterY;
    private final float mDepthZ;
    private final boolean mReverse;
    private Camera mCamera;

    /**
     * Creates a new 3D rotation on the Y axis. The rotation is defined by its
     * start angle and its end angle. Both angles are in degrees. The rotation
     * is performed around a center point on the 2D space, definied by a pair
     * of X and Y coordinates, called centerX and centerY. When the animation
     * starts, a translation on the Z axis (depth) is performed. The length
     * of the translation can be specified, as well as whether the translation
     * should be reversed in time.
     *
     * @param fromDegrees the start angle of the 3D rotation
     * @param toDegrees the end angle of the 3D rotation
     * @param centerX the X center of the 3D rotation
     * @param centerY the Y center of the 3D rotation
     * @param reverse true if the translation should be reversed, false otherwise
     */
    public Rotate3dAnimation(float fromDegrees, float toDegrees, float centerX, float centerY, float depthZ, boolean reverse) {
        mFromDegrees = fromDegrees;
        mToDegrees = toDegrees;
        mCenterX = centerX;
        mCenterY = centerY;
        mDepthZ = depthZ;
        mReverse = reverse;
    }

    @Override
    public void initialize(int width, int height, int parentWidth, int parentHeight) {
        super.initialize(width, height, parentWidth, parentHeight);
        mCamera = new Camera();
    }

    /**
     *
     * @param interpolatedTime 动画时间点,类似百分比
     * @param t
     */
    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        final float fromDegrees = mFromDegrees;
        float degrees = fromDegrees + ((mToDegrees - fromDegrees) * interpolatedTime);

        final float centerX = mCenterX;
        final float centerY = mCenterY;
        final Camera camera = mCamera;

        final Matrix matrix = t.getMatrix();

        camera.save();
        if (mReverse) {//远离
            camera.translate(0.0f, 0.0f, mDepthZ * interpolatedTime);
        } else {//靠近
            camera.translate(0.0f, 0.0f, mDepthZ * (1.0f - interpolatedTime));
        }
        camera.rotateY(degrees);
        camera.getMatrix(matrix);
        camera.restore();

        //移动旋转中心到布局中心
        matrix.preTranslate(-centerX, -centerY);
        matrix.postTranslate(centerX, centerY);
    }
}
注意:使用的是graphics里的Camera而不是hardware里的
注意:其中的centerX和centerY是中心点位置。由于Camera的变换是以(0,0)点为原点,所以需要进行变换。

b.调用这个Animation

final Rotate3dAnimation animation = new Rotate3dAnimation(0, 180,centerX, centerY, 0, true);
            animation.setDuration(500);//动画持续时间,默认为0
            animation.setFillAfter(true);//这个false的话动画完了会复原
            mButton.startAnimation(animation);

嗯,这样按钮就翻转了。

3.接下来做出按钮切换的效果

这里有两种方法。可以使用两个按钮一起翻转,也可以一个按钮翻90后改变样式再翻回来。
我这里使用一个按钮的方案。
先设置两种状态的动画。(注意在onMeasure后设置,不然中心位置定位到0,0了)

        animationF = new Rotate3dAnimation(0, 90,centerX, centerY, 0, true);
        animationF.setDuration(500);//动画持续时间,默认为0
        animationF.setFillAfter(true);//这个false的话动画完了会复原

        animationB = new Rotate3dAnimation(-90, 0,centerX, centerY, 0, true);
        animationB.setDuration(500);
        animationB.setFillAfter(true);

给0-90度翻转的动画增加监听,动画完成时根据状态标识改变样式和文字,然后再从-90-0度翻转的动画。

animationF.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                if (!showBack) {
                    buttonText.setText("BACK BUTTON");
                    mButton.setBackgroundColor(getResources().getColor(R.color.colorAccent));
                } else { // 背面朝上
                    buttonText.setText("FRONT BUTTON");
                    mButton.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                }
                mButton.startAnimation(animationB);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

三.一个问题:显示不全

翻转的时候发现3d变换扩大了的部分超过了空间原先的显示区域而没有显示出来。
这里涉及到margin和padding的处理。
先给mButton的布局增加margin。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <FrameLayout
        android:id="@+id/mButton"
        android:layout_margin="100dp"
        android:background="@color/colorPrimary"
        android:padding="5dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/buttonText"
            android:text="FRONT BUTTON"
            android:gravity="center"
            android:textColor="@android:color/white"
            android:layout_width="100dp"
            android:layout_height="50dp" />
    </FrameLayout>
</LinearLayout>

在onMeasure处理自定义view的margin和padding。

@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        measureChildren(widthMeasureSpec, heightMeasureSpec);
        centerX=mButton.getMeasuredWidth()/ 2;
        centerY=mButton.getMeasuredHeight() / 2;

        mWidth = 0;
        mHeight = 0;
        //margin
        marginLeft = 0;
        marginTop = 0;
        marginRight = 0;
        marginBottom = 0;
        //padding
        paddingLeft = getPaddingLeft();
        paddingTop = getPaddingTop();
        paddingRight = getPaddingRight();
        paddingBottom = getPaddingBottom();
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View childView = getChildAt(i);
            MarginLayoutParams lp = (MarginLayoutParams) childView.getLayoutParams();
            measureChild(childView, widthMeasureSpec, heightMeasureSpec);
            viewsHeight += childView.getMeasuredHeight();
            viewsWidth = Math.max(viewsWidth, childView.getMeasuredWidth());
            marginLeft = Math.max(0,lp.leftMargin);//最大左边距
            marginTop += lp.topMargin;//上边距之和
            marginRight = Math.max(0,lp.rightMargin);//最大右边距
            marginBottom += lp.bottomMargin;//下边距之和
        }

        mWidth = getMeasuredWidth() + paddingLeft + paddingRight + marginLeft + marginRight;
        mHeight = getMeasuredHeight() + paddingBottom + paddingTop + marginTop + marginBottom;
        setMeasuredDimension(measureWidth(widthMeasureSpec, mWidth), measureHeight(heightMeasureSpec, mHeight));

        //动画
        animationF = new Rotate3dAnimation(0, 90,centerX, centerY, 0, true);
        animationF.setDuration(500);//动画持续时间,默认为0
        animationF.setFillAfter(true);//这个false的话动画完了会复原
        animationB = new Rotate3dAnimation(-90, 0,centerX, centerY, 0, true);
        animationB.setDuration(500);
        animationB.setFillAfter(true);

        animationF.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                if (showBack) {
                    buttonText.setText("BACK BUTTON");
                    mButton.setBackgroundColor(getResources().getColor(R.color.colorAccent));
                } else { // 背面朝上
                    buttonText.setText("FRONT BUTTON");
                    mButton.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                }
                mButton.startAnimation(animationB);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
    }

相关github项目地址:
flippedButton

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,711评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,932评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,770评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,799评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,697评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,069评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,535评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,200评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,353评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,290评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,331评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,020评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,610评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,694评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,927评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,330评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,904评论 2 341

推荐阅读更多精彩内容