ตัวอย่างนี้สาธิตวิธีการสร้างข้อความเคลื่อนไหวจาก TextView หนึ่งไปยังอีกเครื่องหนึ่ง
ขั้นตอนที่ 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:gravity = "center" android:layout_height = "match_parent"> <LinearLayout android:layout_width = "wrap_content" android:layout_height = "wrap_content"> <LinearLayout android:id = "@+id/parent" android:layout_width = "wrap_content" android:layout_height = "wrap_content"> <TextView android:id = "@+id/text" android:textSize = "30dp" android:textAlignment = "center" android:layout_width = "match_parent" android:textColor = "#ff4500" android:layout_height = "wrap_content" android:singleLine = "true" /> </LinearLayout> <Button android:id = "@+id/animate" android:text = "Animated button" android:layout_width = "wrap_content" android:layout_height = "wrap_content" /> </LinearLayout> </RelativeLayout>
ในโค้ดด้านบนนี้ เราได้ใช้มุมมองข้อความและปุ่ม เมื่อผู้ใช้คลิกที่ปุ่ม มุมมองข้อความจะอัปเดต
ขั้นตอนที่ 3 − เพิ่มรหัสต่อไปนี้ใน src/MainActivity.java
package com.example.andy.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView view = findViewById(R.id.text);
final LinearLayout parent = findViewById(R.id.parent);
view.setText("1+2");
Button animate = findViewById(R.id.animate);
animate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Animation slideUp = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_up);
slideUp.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
view.setText("3");
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
parent.startAnimation(slideUp);
}
});
}
} มาลองเรียกใช้แอปพลิเคชันของคุณกัน ฉันคิดว่าคุณได้เชื่อมต่ออุปกรณ์มือถือ Android จริงกับคอมพิวเตอร์ของคุณ ในการรันแอพจาก android studio ให้เปิดไฟล์กิจกรรมของโปรเจ็กต์แล้วคลิกไอคอน Run จากแถบเครื่องมือ เลือกอุปกรณ์มือถือของคุณเป็นตัวเลือก แล้วตรวจสอบอุปกรณ์มือถือของคุณซึ่งจะแสดงหน้าจอเริ่มต้นของคุณ -

ในผลลัพธ์ด้านบนที่แสดงหน้าจอเริ่มต้น เมื่อผู้ใช้คลิกที่ปุ่ม มันจะอัปเดตมุมมองข้อความดังที่แสดงด้านล่าง -

