如何在Android中顯示抖動/搖晃檢視動畫?


此示例演示瞭如何在Android中顯示抖動/搖晃檢視動畫。

步驟1 - 在Android Studio中建立一個新專案,轉到檔案⇒新建專案,並填寫所有必需的詳細資訊以建立一個新專案。

步驟2 - 將以下程式碼新增到res/layout/activity_main.xml。

<?xml version = "1.0" encoding = "utf-8"?>
<RelativeLayout
   xmlns:android = "http://schemas.android.com/apk/res/android"
   xmlns:tools = "http://schemas.android.com/tools"
   android:layout_width = "match_parent"
   android:layout_height = "match_parent">
   <Button
      android:id = "@+id/button"
      android:layout_centerHorizontal = "true"
      android:layout_marginTop = "100dp"
      android:layout_width = "150dp"
      android:text = "Click"
      android:layout_height = "wrap_content"/>
   <ImageView
      android:id = "@+id/imageView"
      android:src = "@mipmap/ic_launcher_round"
      android:layout_width = "match_parent"
      android:layout_height = "300dp" />
</RelativeLayout>

在上面的程式碼中,我們使用了按鈕來顯示影像檢視的抖動動畫。

步驟3 - 將以下程式碼新增到src/MainActivity.java

package com.example.andy.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class MainActivity extends AppCompatActivity {
   ImageView view;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      view = findViewById(R.id.imageView);
      findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            Animation animShake = AnimationUtils.loadAnimation(MainActivity.this, R.anim.shake);
            view.startAnimation(animShake);
         }
      });
   }
}

在上面的程式碼中,當用戶點選按鈕時,它將使用抖動動畫來抖動ImageView。為此,我們需要在anim資料夾中建立一個名為shake.xml的檔案。在shake.xml中新增以下程式碼:

<?xml version = "1.0" encoding = "utf-8"?>
<set xmlns:android = "http://schemas.android.com/apk/res/android">
   <translate android:duration = "150"
      android:fromXDelta = "-10%"
      android:repeatCount = "5"
      android:repeatMode = "reverse"
      android:toXDelta = "10%"/>
</set>

讓我們嘗試執行您的應用程式。我假設您已將您的實際Android移動裝置連線到您的計算機。要從Android Studio執行應用程式,請開啟專案中的一個活動檔案,然後點選執行 工具欄中的圖示。選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示您的預設螢幕 -

現在點選按鈕來抖動背景影像,如下所示:

點選這裡下載專案程式碼

更新於:2019年7月30日

782 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.