此範例為點擊button一次則增加一並顯示在textView上,

長按按鈕將計數器歸零,

onLongClick()必須傳回一個布林值,

表示是否引發長按事件或是點擊事件,

return ture觸發長按事件, return false則觸發點擊

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{ //實作oncClickListener跟onLongClickListener
        TextView textView1;
        Button button1;
        int counter = 0;
        
        @Override
        public void onClick(View v){ //實作監聽器介面中定義的onClick方法
            textView1.setText(String.valueOf(++counter));
    }
        @Override
        public boolean onLongClick(View v){ //實作onLongClick介面定義的方法
            counter = 0;
            textView1.setText("0");
            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表示活動物件本身
        button1.setOnLongClickListener(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) 人氣()