android中实现双击效果

根据对一个View两次单击的时间间隔来判断是单击还是双击事件。如果在这个时间段内单击两次则是双击事件,否则则是单击事件。实现代码如下(一个java文件,一个xml布局文件):

//DoubleClickTest.java

package com.dingzhihu.android.foo;

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

public class DoubleClickTest extends Activity {
  
   private boolean waitDouble = true;
   private static final int DOUBLE_CLICK_TIME = 350;   //两次单击的时间间隔
  
   @Override
   public void onCreate(Bundle savedInstanceState){
      super.onCreate(savedInstanceState);
      this.setContentView(R.layout.double_click_test);
      TextView hello = (TextView)findViewById(R.id.hello);
      hello.setOnClickListener(listener);  
     
   }
   OnClickListener listener = new OnClickListener(){

      @Override
      public void onClick(View v) {
         // TODO Auto-generated method stub
         if(waitDouble == true){
            waitDouble = false;
            Thread thread = new Thread(){
               @Override
               public void run(){
                  try {
                     sleep(DOUBLE_CLICK_TIME);
                     if(waitDouble == false){
                        waitDouble = true;
                        singleClick();
                     }
                  } catch (InterruptedException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
                  }
               }
            };
            thread.start();
         }else{
            waitDouble = true;
            doubleClick();
         }
        
        
      }
     
   };
  
   private void singleClick(){
      System.out.println("single");
   }
  
   private void doubleClick(){
      System.out.println("double");
   }
}  //end

<!--

double_click_test.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:id="@+id/hello"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="hello"
    />
</LinearLayout>

posted @ 2011-03-17 11:09  丁志虎  阅读(2678)  评论(1)    收藏  举报