當使用者對手機進行操作, 即會產生對應事件(event)

例如當使用者按下按鈕, 產生該按鈕的onClick事件,

而我們就是藉由撰寫各種事件之處理來與使用者互動,

事件的發生來源(例如按鈕), 稱為該事件的來源物件,

若要處理這事件則要準備一個處理該事件的監聽物件(或稱監聽器),

當來源物件有事件發生, 就會自動呼叫監聽物件所對應的方法來處理,

此範例中, 將會實作OnClickListener介面為監聽物件,

每點擊一次button以及textView都會加二

MainActivity.java 

package com.example.hellocounter;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity 
    
    implements OnClickListener { //實作OnClickListener介面為監聽物件
        TextView textView1;
        Button button1;
        int counter = 0;
        
        @Override
        public void onClick(View v){ //撰寫監聽介面中定義的onClick方法
            counter += 2;
            textView1.setText(String.valueOf(counter)); //將計數值加二,轉成字串顯示出來
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
textView1 = (TextView) findViewById(R.id.textView1); button1 = (Button) findViewById(R.id.button1); button1.setOnClickListener(this); //登陸監聽物件, this表示MainActivity本身 textView1.setOnClickListener(this);//登陸監聽物件, this表示MainActivity本身 } }

 

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.hellocounter.MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="97dp"
        android:text="0"
        android:textSize="60sp" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="count++" />

</RelativeLayout>

 

arrow
arrow

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