onTouchEvent在DOWN事件裏發送多條相同數據和UP裏終止線程

package com.example.administrator.myapplication;

import android.os.Handler;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity {

    private Handler handler = new Handler();
//    boolean on = false;
    boolean off = false;

    private Runnable runnable = new Runnable() {

        public void run() {
            handler.postDelayed(this,1000);
           Log.d("MainActivity", "hehe");

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final Button tv = (Button) findViewById(R.id.tv);
        tv.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch(event.getAction()){
                    case MotionEvent.ACTION_DOWN:
//                        on = false;

                            handler.postDelayed(runnable,1000);


                        off =true;
                        break;
                    case MotionEvent.ACTION_UP:

                        if (off)
                            handler.removeCallbacks(runnable);
                        break;
                    default:
                        break;
                }
                return false;
            }
        });

    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章