android Button按下及抬起监听事件

首先我们在 布局中,写入Button按钮

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="test.bwie.com.wzq_20170921day20.MainActivity"
    >

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btn"
        android:layout_gravity="center"
        android:text="点我有惊喜"/>

</LinearLayout>

在MainActivity 中使用  OnTouchListener 的监听事件

package test.bwie.com.wzq_20170921day20;

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn = (Button) findViewById(R.id.btn);
        //监听
        btn.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction() == MotionEvent.ACTION_DOWN){
                    Toast.makeText(MainActivity.this,"按下了" ,Toast.LENGTH_SHORT).show();
                    btn.setBackgroundColor(Color.RED);
                }else if(event.getAction() == MotionEvent.ACTION_UP){
                    Toast.makeText(MainActivity.this,"松开了" ,Toast.LENGTH_SHORT).show();
                    btn.setBackgroundColor(Color.BLUE);
                }
                return false;
            }
        });

    }
}


猜你喜欢

转载自blog.csdn.net/w2316/article/details/78047547
今日推荐