实现按钮的长按监听(聂同学的作业)
布局文件:
<androidx.constraintlayout.widget.ConstraintLayout 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”
tools:context=“.MainActivity”>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="长按按钮"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
Mainactivity:
package com.example.onlongclickllstener;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements View.OnLongClickListener {
Button button;//声明按钮的引用
public void onCreate(Bundle savedInstanceState) {//重写的onCreate方法
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) this.findViewById(R.id.button);//得到按钮的引用
button.setTextSize(20);
button.setOnLongClickListener(this);//注册监听
}
public boolean onLongClick(View v) {//实现接口中的方法
if(v == button){//当按下的是按钮时
Toast.makeText(
this,
"长时间按下了按钮",
Toast.LENGTH_SHORT
).show();//显示提示
}
return false;
}}
效果:长按