編輯:Android 開發實例
本節實作一個「球進入」的動畫效果,讓多顆球以不同的運動曲線飛入畫面。
首先是寬高的取得。之所以要動態獲取螢幕寬高,是為了適應 Android 多樣的螢幕尺寸。雖然很多時候可以用 XML 裡的 dip 定位,但更多時候我們需要在程式碼中動態加入元件,而程式碼裡設定的數值都以 px 計算,這樣做出來的軟體或遊戲根本無法良好適配螢幕。因此若非透過 XML 配置而要動態解決,我的做法是將介面寬高各切分為若干份(切得越細,控制越精準,但管理也越費心),再依需要賦予寬與高。
動畫效果方面,這裡用到了一組插值器(Interpolator):
// 寬和高
private int width = 100;
private int height = 100;
//要給元件的動畫集合
private static final int[] INTERPOLATORS = {
android.R.anim.accelerate_interpolator,
android.R.anim.decelerate_interpolator,
android.R.anim.accelerate_decelerate_interpolator,
android.R.anim.anticipate_interpolator,
android.R.anim.overshoot_interpolator,
android.R.anim.anticipate_overshoot_interpolator,
android.R.anim.bounce_interpolator };
每顆球會套用不同的插值器,呈現加速、減速、回彈、彈跳等多樣的運動效果。
元件配置 balls_item.xml:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="horizontal"> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:id="@+id/layout" android:paddingRight="35dip"></LinearLayout> <ImageView android:id="@+id/delete" android:scaleType="fitXY" android:src="@drawable/delete" android:layout_width="30dip" android:layout_height="30dip" android:layout_alignParentRight="true"> </ImageView> </RelativeLayout>
核心的 testBallSliding.java 程式碼:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.balls_item);
width = getWindowManager().getDefaultDisplay().getWidth();
height = getWindowManager().getDefaultDisplay().getHeight();
LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
String[] buttons = list.split(" ");
for (int i = 0; i < buttons.length; i++) {
Button button = new Button(this);
button.setPadding(2, 2, 2, 2);
//這裡控制動畫的顯示位置
Animation animation = new TranslateAnimation(width + 50, i * 40, 0, 0);
//設定動畫的運動效果
animation.setInterpolator(getApplicationContext(), INTERPOLATORS[i
% INTERPOLATORS.length]);
animation.setDuration(4000 - 50 * i);
button.setAnimation(animation);
button.setText(buttons[i]);
button.setBackgroundResource(R.drawable.redball);
ImageView delete = (ImageView) findViewById(R.id.delete);
// 刪除的監聽
// .........
layout.addView(button,new LayoutParams(40, 40));
}
}
這裡先以簡單的範例為後續內容做鋪墊。透過 TranslateAnimation 搭配不同的插值器與錯開的時間參數,就能讓每顆球以各具特色的曲線飛入畫面,營造生動的進場效果。
Android 仿微信朋友圈九宮格圖片查看器實現
打開微信朋友圈,你會發現一個經典的「九宮格」圖片區域,點擊任意一張圖就能進入大圖查看頁,還支援滑動切換與縮放。這樣的交互幾乎是所有社交類應用的標配。本文就帶你從零實現一個
Android 應用本地化:values-local 與多語系字串設定
Android 的本地化機制主要是透過不同資源資料夾來達成。當系統語言改變時,Android 會優先載入符合目前語言環境的資源。 資料夾命名規則 本地化字串通常放在 re
LinearLayout 與 RelativeLayout 搭配實現精準版面:padding、margin、gravity 一次搞懂
四個最容易混淆的概念 padding 和 margin 都叫「邊距」,關鍵差別在於「相對誰」: · padding:控件內容相對控件自身邊緣的距離。· margin:控件
Android 基礎:使用 Fragment 適配不同螢幕與解析度
最近工作繁忙,一個新專案急著上線,很多功能都得重做,一直在寫程式、Debug。今天因為新程式要用 Fragment 來做,雖然以前用過,但沒有仔細研究,於是趁機寫篇文章記