如何使用Android操作的按下事件?
此示例演示如何在Android中使用動作按下事件。
步驟1 −在Android Studio中建立一個新專案,轉到檔案⇒新建專案並填寫所有必需的詳細資訊以建立一個新專案。
步驟2 −將以下程式碼新增到 res/layout/activity_main.xml 中。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:gravity="center" android:layout_height="match_parent" tools:context=".MainActivity" android:orientation="vertical"> <TextView android:id="@+id/actionEvent" android:textSize="40sp" android:layout_marginTop="30dp" android:layout_width="wrap_content" android:layout_height="match_parent" /> </LinearLayout>
在上述程式碼中,我們採用了一個文字檢視來執行操作按下事件。
步驟3 −將以下程式碼新增到 src/MainActivity.java
package com.example.myapplication;
import android.annotation.SuppressLint;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.view.MotionEventCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
TextView textView;
@SuppressLint({"RestrictedApi", "ClickableViewAccessibility"})
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView actionEvent = findViewById(R.id.actionEvent);
actionEvent.setText("Action Down");
actionEvent.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = MotionEventCompat.getActionMasked(event);
if (action == MotionEvent.ACTION_DOWN) {
Toast.makeText(MainActivity.this, "Clicked on textview", Toast.LENGTH_LONG).show();
return true;
}
return false;
}
});
}
}讓我們嘗試執行你的應用程式。我假設你已將你的Android移動裝置與你的電腦連線。要從android studio執行應用,請開啟你專案中的一個活動檔案,然後單擊工具欄中的執行
圖示。選擇你的移動裝置作為選項,然後檢視將顯示你預設螢幕的移動裝置——

單擊此處 下載專案程式碼
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP