編輯:關於 Android 程式設計
Android API Demos 裡藏著不少寫得相當漂亮範例,值得逐一研究。本文就模仿其中一個 3D 變換效果,做出一個「列表翻轉變成圖片、點一下再翻回列表」的圖片瀏覽器。
在 Android 上要做 3D 有兩條路:OpenGL ES 與 Camera。前者功能強大但門檻高,通常用於遊戲或高階特效;若只是簡單的視圖翻轉,Camera 就綽綽有餘。
Camera 提供 rotateX()、rotateY()、rotateZ() 三個方法,傳入角度即可讓視圖繞該軸旋轉。中軸旋轉,本質上就是讓視圖繞 Y 軸轉動。
/**
* 讓視圖繞 Y 軸在兩個角度之間旋轉的動畫,
* 並額外在 Z 軸(深度)方向做位移以強化立體感。
*/
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;
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();
}
@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);
}
}
重點在 applyTransformation():
interpolatedTime 算出當前角度。mReverse 決定位移方向。rotateY() 完成 Y 軸旋轉。preTranslate/postTranslate 組合把旋轉中心移到指定座標。
public class Picture {
private String name; // 圖片名稱
private int resource; // 圖片資源 id
public Picture(String name, int resource) {
this.name = name;
this.resource = resource;
}
public String getName() { return name; }
public int getResource() { return resource; }
}
public class PictureAdapter extends ArrayAdapter<Picture> {
public PictureAdapter(Context context, int textViewResourceId, List<Picture> objects) {
super(context, textViewResourceId, objects);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Picture picture = getItem(position);
View view;
if (convertView == null) {
view = LayoutInflater.from(getContext())
.inflate(android.R.layout.simple_list_item_1, null);
} else {
view = convertView;
}
TextView text1 = (TextView) view.findViewById(android.R.id.text1);
text1.setText(picture.getName());
return view;
}
}
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="@+id/pic_list_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ImageView
android:id="@+id/picture"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitCenter"
android:clickable="true"
android:visibility="gone" />
</RelativeLayout>
ListView 與 ImageView 疊在同一個 RelativeLayout 中,透過切換 visibility 達到「翻面前後」的效果。
public class MainActivity extends Activity {
private RelativeLayout layout;
private ListView picListView;
private ImageView picture;
private PictureAdapter adapter;
private List<Picture> picList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
initPics();
layout = (RelativeLayout) findViewById(R.id.layout);
picListView = (ListView) findViewById(R.id.pic_list_view);
picture = (ImageView) findViewById(R.id.picture);
adapter = new PictureAdapter(this, 0, picList);
picListView.setAdapter(adapter);
picListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
picture.setImageResource(picList.get(position).getResource());
float centerX = layout.getWidth() / 2f;
float centerY = layout.getHeight() / 2f;
// 0 度 → 90 度:讓 ListView 從可見轉為不可見
final Rotate3dAnimation rotation =
new Rotate3dAnimation(0, 90, centerX, centerY, 310.0f, true);
rotation.setDuration(500);
rotation.setFillAfter(true);
rotation.setInterpolator(new AccelerateInterpolator());
rotation.setAnimationListener(new TurnToImageView());
layout.startAnimation(rotation);
}
});
picture.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
float centerX = layout.getWidth() / 2f;
float centerY = layout.getHeight() / 2f;
// 360 度 → 270 度:反向轉回
final Rotate3dAnimation rotation =
new Rotate3dAnimation(360, 270, centerX, centerY, 310.0f, true);
rotation.setDuration(500);
rotation.setFillAfter(true);
rotation.setInterpolator(new AccelerateInterpolator());
rotation.setAnimationListener(new TurnToListView());
layout.startAnimation(rotation);
}
});
}
private void initPics() {
picList.add(new Picture("Bird", R.drawable.bird));
picList.add(new Picture("Winter", R.drawable.winter));
picList.add(new Picture("Autumn", R.drawable.autumn));
picList.add(new Picture("Great Wall", R.drawable.great_wall));
picList.add(new Picture("Water Fall", R.drawable.water_fall));
}
/** ListView 動畫結束後,接著啟動 ImageView 的動畫 */
class TurnToImageView implements AnimationListener {
@Override public void onAnimationStart(Animation animation) { }
@Override
public void onAnimationEnd(Animation animation) {
float centerX = layout.getWidth() / 2f;
float centerY = layout.getHeight() / 2f;
picListView.setVisibility(View.GONE);
picture.setVisibility(View.VISIBLE);
picture.requestFocus();
// 270 度 → 360 度:讓 ImageView 從不可見轉為可見
final Rotate3dAnimation rotation =
new Rotate3dAnimation(270, 360, centerX, centerY, 310.0f, false);
rotation.setDuration(500);
rotation.setFillAfter(true);
rotation.setInterpolator(new AccelerateInterpolator());
layout.startAnimation(rotation);
}
@Override public void onAnimationRepeat(Animation animation) { }
}
/** ImageView 動畫結束後,接著啟動 ListView 的動畫 */
class TurnToListView implements AnimationListener {
@Override public void onAnimationStart(Animation animation) { }
@Override
public void onAnimationEnd(Animation animation) {
float centerX = layout.getWidth() / 2f;
float centerY = layout.getHeight() / 2f;
picture.setVisibility(View.GONE);
picListView.setVisibility(View.VISIBLE);
picListView.requestFocus();
// 90 度 → 0 度:回到原點
final Rotate3dAnimation rotation =
new Rotate3dAnimation(90, 0, centerX, centerY, 310.0f, false);
rotation.setDuration(500);
rotation.setFillAfter(true);
rotation.setInterpolator(new AccelerateInterpolator());
layout.startAnimation(rotation);
}
@Override public void onAnimationRepeat(Animation animation) { }
}
}
點擊列表項時,先把 ImageView 的圖換成被點的那張,算出版面中心作為旋轉軸,然後啟動 0°→90° 的動畫並掛上 TurnToImageView。動畫結束後在回呼中把 ListView 設為 GONE、ImageView 設為 VISIBLE,再跑 270°→360°,視覺上就形成「列表沿中軸翻走、圖片沿中軸翻入」的連貫效果。
反向流程同理:先讓 ImageView 從 360° 轉到 270°(確保方向與進入時相反),結束後切換可見性,再讓 ListView 從 90° 轉回 0°。
這個範例最值得學的不是動畫本身,而是用 AnimationListener 把兩段動畫串成序列的技巧。任何需要「A 做完接著做 B」的動畫,都可以用這個模式處理。另外注意角度的選擇:進入用 0→90,出現用 270→360,兩者相加為 360 度,如此翻入與翻出的方向才會一致而不突兀。
若要在新專案實作,建議改用 ViewPropertyAnimator 搭配 rotationY 與 cameraDistance,或使用 ViewFlipper 與 TransitionManager,能少寫很多樣板程式碼,也更容易維護。
Android 網路編程 UDP 實戰(三):搜索區域網內的所有設備
承接前面的 UDP 主題,本篇主要探討如何在區域網中搜索所有設備。這個需求在物聯網應用中相當常見,也頗具綜合性,因此特別將它放進標題。文末再補充一些網路編程的常見問題。
360奇酷手機刷機教學 Recovery與工具兩種方案
360奇酷手機出自酷派與360的合資公司,奇酷與酷派均採用安卓系統。那麼奇酷、酷派手機該怎麼刷機?下面小編提供兩種思路。 手機出現異常時,可以先嘗試恢復出廠設定。需特別注
動手玩 Android L:開發者預覽版的取得與安裝步驟
Google 在週三發表了 Android 的下一個重要版本 Android L。不過目前釋出的只是預覽版本,完整的開發者預覽版稍後才會跟上,正式版則預計在今年秋天登場
Android 開發之適配器模式初探
寫 Android 時我們天天在用 Adapter——它把資料與 UI 串在一起,ListView、Spinner、GridView 都靠它變得靈活。而 Adapter