Android自定義控件之翻轉(zhuǎn)按鈕的示例代碼
本文介紹了Android自定義控件之翻轉(zhuǎn)按鈕的示例代碼,分享給大家,具體如下:
先看一下效果
一.先定義控件的基本結(jié)構(gòu)
這里我們定義一個(gè)容器,所以是在ViewGroup的基礎(chǔ)上擴(kuò)展。
簡(jiǎn)單起見(jiàn),直接使用擴(kuò)展自ViewGroup的LinearLayout,并將我們的控件擴(kuò)展自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.自定義控件開(kāi)門(mén)三步走
構(gòu)造函數(shù),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); } //測(cè)量子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>
現(xiàn)在可以看到一個(gè)最基本的自定義控件已經(jīng)可以使用了。
二.接下來(lái)是重點(diǎn),控件真正“自定義”的部分。
1.添加自定義事件
a.先定義自定義事件接口
/** * 定義接口 */ public interface IMyClick{ public void onMyClick(String str); } /** * 初始化接口變量 */ IMyClick iMyClick=null; /** * 自定義事件監(jiān)聽(tīng) * @param _iMyClick */ public void setOnMyClickListener(IMyClick _iMyClick){ iMyClick=_iMyClick; }
b.添加按鈕點(diǎn)擊事件的監(jiān)聽(tīng)并調(diào)用接口傳參
mButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { iMyClick.onMyClick("clicked me"); flipMe(); } });
c.父級(jí)Activity監(jiān)聽(tīng)事件
fButton=(flippedButton) findViewById(R.id.flippedButton); fButton.setOnMyClickListener(new flippedButton.IMyClick(){ @Override public void onMyClick(String str) { Log.d(LOG_TAG,str); } });
2.繪制按鈕翻轉(zhuǎn)的動(dòng)畫(huà)
這里的3d變換需要用到Camera(android.graphics.Camera)、Matrix。
這里可以想象成用Camera拍攝原件的圖形,并將拍攝得到的bitmap傳入matrix再繪制到Canvas。
而改變Camera鏡頭角度就可以得到縮放變形后的圖像以實(shí)現(xiàn)3d效果。
參考官方demo里的這個(gè)工具類(lèi)的范例Rotate3dAnimation.java(其實(shí)是照搬)
a.先建一個(gè)3d變換的工具類(lèi):
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 動(dòng)畫(huà)時(shí)間點(diǎn),類(lèi)似百分比 * @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) {//遠(yuǎn)離 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(); //移動(dòng)旋轉(zhuǎn)中心到布局中心 matrix.preTranslate(-centerX, -centerY); matrix.postTranslate(centerX, centerY); } }
注意:使用的是graphics里的Camera而不是hardware里的
注意:其中的centerX和centerY是中心點(diǎn)位置。由于Camera的變換是以(0,0)點(diǎn)為原點(diǎn),所以需要進(jìn)行變換。
b.調(diào)用這個(gè)Animation
final Rotate3dAnimation animation = new Rotate3dAnimation(0, 180,centerX, centerY, 0, true); animation.setDuration(500);//動(dòng)畫(huà)持續(xù)時(shí)間,默認(rèn)為0 animation.setFillAfter(true);//這個(gè)false的話(huà)動(dòng)畫(huà)完了會(huì)復(fù)原 mButton.startAnimation(animation);
嗯,這樣按鈕就翻轉(zhuǎn)了。
3.接下來(lái)做出按鈕切換的效果
這里有兩種方法??梢允褂脙蓚€(gè)按鈕一起翻轉(zhuǎn),也可以一個(gè)按鈕翻90后改變樣式再翻回來(lái)。
我這里使用一個(gè)按鈕的方案。
先設(shè)置兩種狀態(tài)的動(dòng)畫(huà)。(注意在onMeasure后設(shè)置,不然中心位置定位到0,0了)
animationF = new Rotate3dAnimation(0, 90,centerX, centerY, 0, true); animationF.setDuration(500);//動(dòng)畫(huà)持續(xù)時(shí)間,默認(rèn)為0 animationF.setFillAfter(true);//這個(gè)false的話(huà)動(dòng)畫(huà)完了會(huì)復(fù)原 animationB = new Rotate3dAnimation(-90, 0,centerX, centerY, 0, true); animationB.setDuration(500); animationB.setFillAfter(true);
給0-90度翻轉(zhuǎn)的動(dòng)畫(huà)增加監(jiān)聽(tīng),動(dòng)畫(huà)完成時(shí)根據(jù)狀態(tài)標(biāo)識(shí)改變樣式和文字,然后再?gòu)?90-0度翻轉(zhuǎn)的動(dòng)畫(huà)。
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) { } });
三.一個(gè)問(wèn)題:顯示不全
翻轉(zhuǎn)的時(shí)候發(fā)現(xiàn)3d變換擴(kuò)大了的部分超過(guò)了空間原先的顯示區(qū)域而沒(méi)有顯示出來(lái)。
這里涉及到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)); //動(dòng)畫(huà) animationF = new Rotate3dAnimation(0, 90,centerX, centerY, 0, true); animationF.setDuration(500);//動(dòng)畫(huà)持續(xù)時(shí)間,默認(rèn)為0 animationF.setFillAfter(true);//這個(gè)false的話(huà)動(dòng)畫(huà)完了會(huì)復(fù)原 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) { } }); }
相關(guān)github項(xiàng)目地址:flippedButton
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android實(shí)現(xiàn)帶有刪除按鈕的EditText示例代碼
本文給大家介紹一個(gè)很實(shí)用的小控件,就是在Android系統(tǒng)的輸入框右邊加入一個(gè)小圖標(biāo),點(diǎn)擊小圖標(biāo)可以清除輸入框里面的內(nèi)容,IOS上面直接設(shè)置某個(gè)屬性就可以實(shí)現(xiàn)這一功能,但是Android原生EditText不具備此功能,所以要想實(shí)現(xiàn)這一功能我們需要重寫(xiě)EditText。下面來(lái)看看吧。2016-12-12Android利用Badge組件實(shí)現(xiàn)未讀消息小紅點(diǎn)
在?App?的運(yùn)營(yíng)中,活躍度是一個(gè)重要的指標(biāo),日活/月活……為了提高活躍度,就發(fā)明了小紅點(diǎn)。這一篇,來(lái)介紹一個(gè)徽標(biāo)(Badge)組件,能夠快速搞定應(yīng)用內(nèi)的小紅點(diǎn),希望對(duì)大家有所幫助2023-01-01android主線(xiàn)程和子線(xiàn)程之間消息傳遞詳解
這篇文章主要介紹了android主線(xiàn)程和子線(xiàn)程之間消息傳遞詳解,主線(xiàn)程發(fā)送消息到子線(xiàn)程,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-01-01Android自定義Dialog實(shí)現(xiàn)通用圓角對(duì)話(huà)框
這篇文章主要為大家詳細(xì)介紹了Android自定義Dialog實(shí)現(xiàn)通用圓角對(duì)話(huà)框,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-11-11Android開(kāi)發(fā)重寫(xiě)Animation實(shí)現(xiàn)下拉圖片后彈射回去效果示例
這篇文章主要介紹了Android開(kāi)發(fā)重寫(xiě)Animation實(shí)現(xiàn)下拉圖片后彈射回去效果,結(jié)合實(shí)例形式分析了Android自定義類(lèi)繼承Animation實(shí)現(xiàn)圖片彈射效果的相關(guān)操作技巧,需要的朋友可以參考下2017-10-10Android 實(shí)現(xiàn)旋轉(zhuǎn)木馬的音樂(lè)效果
大家一定在百度音樂(lè)上在線(xiàn)聽(tīng)過(guò)歌,有沒(méi)有注意到那個(gè)旋轉(zhuǎn)的唱片,本篇文章主要介紹在Android上如何實(shí)現(xiàn)這樣的功能,有需要的小伙伴可以參考下2016-07-07eclipse中運(yùn)行monkeyrunner腳本之環(huán)境搭建(4)
這篇文章主要為大家詳細(xì)介紹了eclipse中運(yùn)行monkeyrunner腳本之環(huán)境搭建的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-12-12Android開(kāi)發(fā)之毛玻璃效果實(shí)例代碼
這篇文章主要給大家分享android開(kāi)發(fā)之毛玻璃效果的實(shí)例代碼,非常具有參考借鑒價(jià)值,感興趣的朋友一起學(xué)習(xí)吧2016-05-05Android 使用 RxJava2 實(shí)現(xiàn)倒計(jì)時(shí)功能的示例代碼
本篇文章主要介紹了Android 使用 RxJava2 實(shí)現(xiàn)倒計(jì)時(shí)功能的示例代碼,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-03-03