如何在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"/> <LinearLayout android:id = "@+id/view" android:background = "#a6e1aa" android:orientation = "vertical" android:layout_alignParentBottom = "true" android:layout_width = "match_parent" android:layout_margin = "20dp" android:layout_height = "200dp"> <EditText android:hint = "User name" android:layout_width = "match_parent" android:layout_height = "wrap_content" /> <EditText android:hint = "Password" android:layout_width = "match_parent" android:layout_height = "wrap_content" /> </LinearLayout> </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.TranslateAnimation; import android.widget.Button; import android.widget.LinearLayout; public class MainActivity extends AppCompatActivity { boolean opened; LinearLayout view; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); view = findViewById(R.id.view); view.setVisibility(View.INVISIBLE); findViewById(R.id.button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(!opened){ view.setVisibility(View.VISIBLE); TranslateAnimation animate = new TranslateAnimation( 0, 0, view.getHeight(), 0); animate.setDuration(500); animate.setFillAfter(true); view.startAnimation(animate); } else { view.setVisibility(View.INVISIBLE); TranslateAnimation animate = new TranslateAnimation( 0, 0, 0, view.getHeight()); animate.setDuration(500); animate.setFillAfter(true); view.startAnimation(animate); } opened = !opened; } }); } }
在上面的程式碼中,我們使用平移動畫顯示和隱藏線性佈局,如下所示 -
要顯示檢視,請使用以下程式碼 -
TranslateAnimation animate = new TranslateAnimation( 0, 0, view.getHeight(), 0); animate.setDuration(500); animate.setFillAfter(true); view.startAnimation(animate); To hide the view, use the following code - TranslateAnimation animate = new TranslateAnimation( 0, 0, 0, view.getHeight()); animate.setDuration(500); animate.setFillAfter(true); view.startAnimation(animate);
讓我們嘗試執行您的應用程式。我假設您已將您的實際Android移動裝置連線到您的計算機。要從Android Studio執行應用程式,請開啟您的一個專案活動檔案,然後單擊工具欄中的執行 圖示。選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示您的預設螢幕 -
當用戶點選按鈕時,它將顯示如下螢幕,現在點選同一個按鈕隱藏檢視,如下所示 -
點選此處下載專案程式碼
廣告