AS之OnTouchEvent方法

重写OnTouchEvent()方法

废话不多说,上例子

package com.example.a4_7;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.view.MotionEvent;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        MyButton button = new MyButton(this);
        button.setText("点我");
        button.setTextSize(20);
        button.setAllCaps(false);  设置字体按原样式输出
        setContentView(button);
    }
     创建MyButton类来重写OnTouchEvent方法
    @SuppressLint("AppCompatCustomView")
    class MyButton extends Button {
        public MyButton(Context context) {
            super(context);
        }
      重写onTouchEvent方法实现显示内容
        public boolean onTouchEvent(MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    Toast.makeText(MainActivity.this, "按钮被按下", Toast.LENGTH_SHORT).show();
                    break;
                case MotionEvent.ACTION_MOVE:
                    Toast.makeText(MainActivity.this, "按钮被移动", Toast.LENGTH_SHORT).show();
                    break;
                case MotionEvent.ACTION_UP:
                    Toast.makeText(MainActivity.this, "按钮被抬起", Toast.LENGTH_SHORT).show();
                    break;
            }
            return super.onTouchEvent(event);
        }

    }
}

显示如图
在这里插入图片描述

发布了15 篇原创文章 · 获赞 0 · 访问量 138

猜你喜欢

转载自blog.csdn.net/qq_44230959/article/details/105643251