您好,登錄后才能下訂單哦!
這篇文章主要介紹了如何在Android中對按鈕進行翻轉,此處通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考價值,需要的朋友可以參考下:
Android是一種基于Linux內核的自由及開放源代碼的操作系統,主要使用于移動設備,如智能手機和平板電腦,由美國Google公司和開放手機聯盟領導及開發。
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) { } }); }
到此這篇關于如何在Android中對按鈕進行翻轉的文章就介紹到這了,更多相關如何在Android中對按鈕進行翻轉的內容請搜索億速云以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持億速云!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。