重写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);
}
}
}
显示如图