編輯:關於 Android 程式設計
上一篇《Android 動畫之一:Drawable Animation》講了逐幀動畫——依次顯示一系列圖片,最典型的用途是加載進度動畫。本篇接着往下走,談談 View Animation。
View Animation 也就是很多書裡所說的 Tweened Animation(補間動畫)。它分為四大類,分別對應四種變化:
AlphaAnimation:透明度變化RotateAnimation:旋轉ScaleAnimation:尺寸縮放TranslateAnimation:位置平移一個 View Animation 的效果由四個要素決定:
你只要給出這四項,中間每一幀是什麼樣子,系統會自動算出來——這正是「補間」二字的含義。
前三個要素都好理解。第四個 Interpolator 稍微特別,這個單詞的中文翻譯一直比較混亂(有譯作「插值器」、「動畫插值」、「補間干預器」)。它的作用是決定動畫進行過程中的速度變化曲線。比如把一個按鈕從屏幕左側移到右側:可以勻速移動,可以一開始飛快然後減速停下(DecelerateInterpolator),也可以慢慢起步越跑越快(AccelerateInterpolator),還有先加速再減速(AccelerateDecelerateInterpolator)、有彈性回彈(OvershootInterpolator / BounceInterpolator)等等。下面會具體演示。
先建工程 ViewAnimationDemo,新建布局 animationjavacode.xml:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://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=".MainActivity" >
<TextView
android:id="@+id/translation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="50dp"
android:text="我要移動" />
<TextView
android:id="@+id/rotate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/translation"
android:layout_marginBottom="50dp"
android:text="我要旋轉" />
<TextView
android:id="@+id/scale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/rotate"
android:layout_marginBottom="50dp"
android:text="我要放大" />
<TextView
android:id="@+id/alpha"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/scale"
android:layout_marginBottom="50dp"
android:text="我要變暗" />
<Button
android:id="@+id/fire"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/alpha"
android:text="啟動動畫" />
</RelativeLayout>
對應的 Activity:
public class AnimCodeActivity extends Activity {
private TextView translation;
private TextView rotate;
private TextView scale;
private TextView alpha;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.animationjavacode);
translation = (TextView) findViewById(R.id.translation);
rotate = (TextView) findViewById(R.id.rotate);
scale = (TextView) findViewById(R.id.scale);
alpha = (TextView) findViewById(R.id.alpha);
button = (Button) findViewById(R.id.fire);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 1 & 2: 確定起始狀態與結束狀態
TranslateAnimation tAnim = new TranslateAnimation(0, 400, 0, 0);
// 橫向位移 400 個單位
RotateAnimation rAnima = new RotateAnimation(0, 70);
// 順時針旋轉 70 度
ScaleAnimation sAnima = new ScaleAnimation(0, 5, 0, 5);
// 橫向放大 5 倍,縱向放大 5 倍
AlphaAnimation aAnima = new AlphaAnimation(1.0f, 0.0f);
// 從全不透明變為全透明
// 3: 確定持續時間(毫秒)
tAnim.setDuration(2000);
rAnima.setDuration(2000);
sAnima.setDuration(2000);
aAnima.setDuration(2000);
// 4: 確定 Interpolator,效果為先加速後減速
tAnim.setInterpolator(new AccelerateDecelerateInterpolator());
// 啟動動畫
translation.startAnimation(tAnim);
rotate.startAnimation(rAnima);
scale.startAnimation(sAnima);
alpha.startAnimation(aAnima);
}
});
}
}
從代碼中不難看出,整個流程就是「定起止 → 定時長 → 定插值器 → 啟動」。如果不設置持續時間,默認值極短(約 300ms 甚至更短),肉眼幾乎看不到效果,這也是新手常犯的遺漏。默認的 Interpolator 是勻速。
按官方文檔,View Animation 的 XML 格式如下:
<?xml version="1.0" encoding="utf-8"?>
<set android:interpolator="@[package:]anim/interpolator_resource"
android:shareInterpolator="true"
xmlns:android="https://schemas.android.com/apk/res/android" >
<alpha android:fromAlpha="float" android:toAlpha="float" />
<scale android:fromXScale="float" android:toXScale="float"
android:fromYScale="float" android:toYScale="float"
android:pivotX="float" android:pivotY="float" />
<translate android:fromXDelta="float" android:toXDelta="float"
android:fromYDelta="float" android:toYDelta="float" />
<rotate android:fromDegrees="float" android:toDegrees="float"
android:pivotX="float" android:pivotY="float" />
<set> ... </set>
</set>
該文件只能有一個根節點,可以是 <set>、<alpha>、<scale>、<translate>、<rotate>。其中 <set> 可以包含子節點,也可以嵌套 <set>,從而構造出任意複雜的動畫序列。
需要特別說明的兩個屬性:
android:interpolator:指定所用的插值器,可以是系統自帶的(如 @android:anim/accelerate_interpolator),也可以是自定義的。
android:shareInterpolator:是否把該插值器共享給所有子節點。設為 false 時,子節點可以各自指定自己的插值器。
另外兩個容易困惑的屬性是 android:pivotX 與 android:pivotY。pivot 是「軸心」的意思,這兩個屬性定義的是縮放與旋轉的基準點,默認為左上角。若兩者都設為 50%,則以中心為軸心變換。這也是為什麼直接寫 ScaleAnimation(0, 5, 0, 5) 時物體會「飛走」——默認軸心在左上角,放大後視覺位置發生了偏移。
一般把定義動畫的 XML 放在 res/anim 目錄下。新建 anim 文件夾與 myanim.xml:
<set android:shareInterpolator="false"
xmlns:android="https://schemas.android.com/apk/res/android" >
<scale android:duration="1000"
android:fillAfter="false"
android:fromXScale="1.0"
android:fromYScale="1.0"
android:interpolator="@android:anim/accelerate_decelerate_interpolator"
android:pivotX="50%"
android:pivotY="50%"
android:toXScale="1.4"
android:toYScale="0.6" >
<set android:interpolator="@android:anim/accelerate_interpolator"
android:startOffset="1000" >
<scale android:duration="400"
android:fromXScale="1.4"
android:fromYScale="0.6"
android:pivotX="50%"
android:pivotY="50%"
android:toXScale="0.0"
android:toYScale="0.0" />
<rotate android:duration="400"
android:fromDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="60" />
</set>
</scale>
</set>
結構是:唯一的根節點 <set> 有兩個子節點——一個 <scale> 和一個嵌套的 <set>;嵌套的 <set> 又包含自己的 <scale> 與 <rotate>。
補充幾個新出現的屬性:
android:fillAfter:第一個例子中,動畫結束後 helloworld 又回到了原位。把 fillAfter 設為 true,動畫會保持結束狀態。但要注意,這只是「視覺上保持」,下面會詳細說明。
android:startOffset:定義動畫推遲多久開始。通過它可以設計前後按序發生的動畫序列。注意除最後一個動畫外,其餘都應設置 fillAfter 為 true,否則會在下一段開始時跳回原位。
布局文件裡放一張圖片一個按鈕,點擊按鈕觸發動畫:
public class AnimaXmlActivity extends Activity {
private Button btn;
private ImageView img;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_anima_xml);
btn = (Button) findViewById(R.id.xml_btn);
img = (ImageView) findViewById(R.id.xmlAnimImg);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 一般使用 AnimationUtils 讀取 XML 中定義的動畫
Animation anim = AnimationUtils.loadAnimation(
AnimaXmlActivity.this, R.anim.myanim);
img.startAnimation(anim);
}
});
}
}
用 AnimationUtils.loadAnimation() 加載,再調用 View.startAnimation() 啟動,就這麼簡單。
做一個常見的側滑效果(類似網易新聞那種):
這個效果實現起來並不難,但很多人會用 AsyncTask 開線程逐像素改 margin,結果發現經常卡頓。改用動畫會平滑得多。
新建項目 SwipeWithAnim,布局 activity_main.xml:
<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<!-- 屏幕顯示內容 -->
<View
android:id="@+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#e23451" >
<!-- 左側隱去的菜單,通過負 margin 藏在屏幕外 -->
<LinearLayout
android:id="@+id/menu"
android:layout_width="400dp"
android:layout_height="match_parent"
android:layout_gravity="left"
android:layout_marginLeft="-380dp"
android:orientation="horizontal" >
<View
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#eeeee1" />
<!-- 只留 20dp 透明區域在屏幕左側,用於觸發 onTouch -->
<View
android:id="@+id/dragArea"
android:layout_width="20dp"
android:layout_height="match_parent"
android:background="#00000000" />
</LinearLayout>
</View>
</FrameLayout>
思路是:菜單通過 -380dp 的負 margin 藏在屏幕左側,只露出 20dp 的透明觸摸區。Activity 代碼如下:
public class MainActivity extends Activity {
private View menu;
private final static int SHOW_MENU = 1;
private final static int HIDE_MENU = -1;
private int swipe_tag = SHOW_MENU;
private int max_menu_margin = 0; // 完全展開時的 margin
private int min_menu_margin; // 完全隱藏時的 margin
private float beginX;
private float latestX;
private float diffX;
private float latestMargin;
private FrameLayout.LayoutParams lp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
menu = findViewById(R.id.menu);
lp = (FrameLayout.LayoutParams) menu.getLayoutParams();
min_menu_margin = lp.leftMargin;
menu.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = MotionEventCompat.getActionMasked(event);
switch (action) {
case MotionEvent.ACTION_DOWN:
beginX = event.getX();
break;
case MotionEvent.ACTION_MOVE:
latestX = event.getX();
diffX = latestX - beginX;
// 根據移動方向判斷是展開還是收起
swipe_tag = diffX > 0 ? SHOW_MENU : HIDE_MENU;
latestMargin = lp.leftMargin + diffX;
if (latestMargin > min_menu_margin
&& latestMargin < max_menu_margin) {
lp.leftMargin = (int) latestMargin;
menu.setLayoutParams(lp);
}
break;
case MotionEvent.ACTION_UP:
TranslateAnimation tAnim;
if (swipe_tag == SHOW_MENU) {
tAnim = new TranslateAnimation(
0, max_menu_margin - latestMargin, 0, 0);
tAnim.setInterpolator(new DecelerateInterpolator());
tAnim.setDuration(800);
menu.startAnimation(tAnim);
} else {
tAnim = new TranslateAnimation(
0, min_menu_margin - latestMargin, 0, 0);
tAnim.setDuration(800);
menu.startAnimation(tAnim);
}
// 關鍵:在動畫結束時真正移動 menu 的位置
tAnim.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) { }
@Override
public void onAnimationRepeat(Animation animation) { }
@Override
public void onAnimationEnd(Animation animation) {
if (swipe_tag == SHOW_MENU) {
lp.leftMargin = max_menu_margin;
} else {
lp.leftMargin = min_menu_margin;
}
menu.setLayoutParams(lp);
menu.clearAnimation();
}
});
break;
}
return true;
}
});
}
}
(截圖軟件有掉幀,真機上測試是平滑的。)
上面示例中那段 setAnimationListener 的代碼,正是為了應對 View Animation 最容易被忽視的特性:
補間動畫只是「畫」出來的視覺效果,View 本身的屬性並沒有改變。
也就是說,當一個按鈕通過 TranslateAnimation 移動到另一個位置後:
getLeft() / getTop() 依然是原來的值。所以示例中必須監聽 AnimationListener,在動畫結束的瞬間通過修改 leftMargin 把菜單「真正」挪過去,然後 clearAnimation() 清除視覺殘留。這一步不做,菜單就會「彈回去」。
同理,fillAfter="true" 也只是讓視覺停留在末幀,點擊區域還是原來那塊。要真正做到「移動後可點擊」,只有兩條路:一是像示例那樣在動畫結束後修改真實布局參數;二是改用屬性動畫(Property Animation)。
Android 3.0(API 11)引入了 ObjectAnimator / ValueAnimator,它直接修改對象的真實屬性,動畫結束後狀態自然保持,也不再有所謂「點擊位置錯位」的問題:
ObjectAnimator animator = ObjectAnimator.ofFloat(menu, "translationX", 0f, 380f); animator.setDuration(800); animator.start();
或者更簡潔的 ViewPropertyAnimator( also API 12+):
menu.animate().translationX(380f).setDuration(800).start();
選型建議:
AnimatorSet 或 AnimationSet,兩者都支持 startOffset 做編排。本文兩個示例的完整源碼:ViewAnimationDemo、SwipeWithAnim。
Android 自定義控件:打造百分比圓環進度條
先來看看最終效果: 分析 這個進度條可以拆成三個部分: 1. 中間的圓; 2. 外邊的圓環; 3. 中間的文字。 分步繪製 這三部分都需要我們自己畫出來,因此要準備三根
Android 四大資料儲存方式全解析:SharedPreferences、SQLite、File 與 ContentProvider
Android 提供的四種儲存方式 Android 為開發者準備了以下四種資料儲存方式: SharedPreferences SQLite File ContentPr
Android 集成百度翻譯 SDK:簽名生成與異步請求實戰
本文記錄在 Android 工程中接入百度翻譯開放平台的完整過程,開發環境為 Android Studio。 一、申請憑證與下載 Demo 先到百度翻譯開放平台(http
Android 常用布局解析:線性、幀、表格與相對布局
為什麼要使用 XML 描述布局Android 常用 XML 來宣告介面布局,讓畫面呈現與程式邏輯分離。這樣不僅方便修改樣式,也能降低後續維護成本。開發者也可以透過視覺化工