一個event listenerview類別中,是一個介面並包含一個callback的方法,當使用者與View進行物件互動,此listener就會被註冊,這些方法就會將由android framework所呼叫。

方法說明如下:

onClick():屬於View.OnClickListener 表示當使用者觸碰到某一個項目時。

onLongClick:屬於View.OnLongClickListener表示當使用者觸碰到某一項目且按住不放時。

onFocusChange():屬於View.OnFocusChangeListener表示移置項目上或移開到別的項目。

onKey():屬於View.OnKeyListener表示當使用者按下或放開一個鑑。

onTouch():屬於View.OnTouchListener表示當使用者完成一個觸碰事件的動作,包含螢幕放開、按下或是其他移動手勢。

onCreateContextMenu():屬於View.OnCreateContextMenuListener表示當一個ContextMenu被建立時。

小試身手小範例:

替一個按鈕註冊一個onClickListener

Java

import android.app.Activity;

import android.content.Context;

import android.os.Bundle;

import android.view.Gravity;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.Toast;

publicclass TestExam004 extends Activity {

    /** Called when the activity is first created. */

    @Override

    publicvoid onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

      

        OnClickListener mSendListener = new OnClickListener(){

         publicvoid onClick(View v){

             Toast.makeText(TestExam004.this, "Yes", Toast.LENGTH_LONG).show();

         }

    }; 

        Button button = (Button)findViewById(R.id.send);

        button.setOnClickListener(mSendListener);

    }

}

Main.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    >

<TextView 

    android:layout_width="fill_parent"

    android:layout_height="wrap_content"

    android:text="@string/hello"

    />

<Button

    android:id="@+id/send"

    android:text="send"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

/>

</LinearLayout>

Toast01.jpg  

arrow
arrow

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