转载请注明出处:触摸响应(点击/长按/触摸坐标)_Mr_Leixiansheng的博客-CSDN博客
很简单,不详细介绍。
1、setOnClickListener
2、setOnLongClickListener
3、onTouchEvent
package com.example.administrator.test4;
import android.support.annotation.FloatRange;
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 {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "你点击了按钮", Toast.LENGTH_SHORT).show();
}
});
button.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
Toast.makeText(MainActivity.this, "你长按了按钮", Toast.LENGTH_SHORT).show();
return true;
}
});
}
//触摸监听
@Override
public boolean onTouchEvent(MotionEvent event) {
//获取触摸坐标
Float X = event.getX();
Float Y = event.getY();
Toast.makeText(MainActivity.this, "你触摸了屏幕" + "X:"+ X + "Y:" + Y, Toast.LENGTH_SHORT).show();
return super.onTouchEvent(event);
}
}
Kotlin写法:
package com.leixiansheng.kotlintest
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.MotionEvent
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button.setOnClickListener {
Toast.makeText(this, "你点击了按钮", Toast.LENGTH_SHORT).show();
}
button.setOnLongClickListener {
Toast.makeText(application, "你长按了按钮", Toast.LENGTH_SHORT).show();
true
}
}
override fun onTouchEvent(event: MotionEvent): Boolean {
val touchX =event.x
val touchY =event.y
Toast.makeText(application, "你触摸了屏幕" + "touchX:"+ touchX + "touchY:" + touchY, Toast.LENGTH_SHORT).show();
return super.onTouchEvent(event)
}
}