若想分別偵測"按下","放開"兩個動作,

則可使用onTouch()事件,

此範例為當使用者按住螢幕手機開始震動,

直到放開或是震動五秒為止。

 

MainActivity.java

package com.example.tovibrate;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.TextView;

public class MainActivity extends Activity implements OnTouchListener{

    @Override
/*參數v是事件來源物件, e是儲存有觸控資訊的物件*/ public boolean onTouch(View v, MotionEvent e) //實作onTouchListener觸控監聽器介面的方法 { Vibrator vb = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
if(e.getAction() == MotionEvent.ACTION_DOWN){ //按下螢幕中間的文字 vb.vibrate(5000); //震動五秒 } else if(e.getAction() == MotionEvent.ACTION_UP){ //放開螢幕中間的文字 vb.cancel(); //停止震動 } return true; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView txv = (TextView) findViewById(R.id.textView1); txv.setOnTouchListener(this); //登錄觸控監聽物件 } }

 

activity_main.xml

<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.tovibrate.MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="to Vibrate" />

</RelativeLayout>

 

 

arrow
arrow
    文章標籤
    android onTouch()
    全站熱搜

    Will 發表在 痞客邦 留言(0) 人氣()