在開發程式時,常需要處理來自不同元件的同類事件,

這時必須在事件處理的方法中分辨事件的來源物件,並依據來源進行不同的行為。

而我們可以使用getId()此方法來判斷來源物件

此範例以長按按鈕計數加二,長按計數值(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.view.View.OnLongClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity 
    
    implements OnClickListener, OnLongClickListener{
        TextView textView1;
        Button button1;
        int counter = 0;
        
        @Override
        public void onClick(View v){
            textView1.setText(String.valueOf(++counter));
    }
        @Override
        public boolean onLongClick(View v){
            if(v.getId() == R.id.textView1) //判斷來源物件是否為顯示計數值的textView, 若是就將計數器歸零
            {
                counter = 0;
                textView1.setText("0");
            }else{                          //若來源物件不為textView, 計數累加2
                counter += 2;
                textView1.setText(String.valueOf(counter));
            }
            return true;
        }
    @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物件本身
        button1.setOnLongClickListener(this);  //MainActivity物件登錄為按鈕的長按監聽器
        textView1.setOnLongClickListener(this);//MainActivity物件登錄textView的長按監聽器
    }
}

 

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) 人氣()