OnKeyListener接口是对设备的键盘进行监听的接口,当对界面上的View注册了该监听器,则当该View获得焦点并触发了键盘事件时,程序会调用其接口中的onKey()方法。接口中需要实现的方法的定义方式如下:
public boolean onKey(View v, int keyCode, KeyEvent keyEvent)
参数v表示事件的事件源。
参数keyCode表示键盘的键盘码。
参数keyEvent 表示键盘事件封装类的对象,其中包含了事件的详细信息。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:orientation="vertical"
android:gravity="center_horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tv_choose"
android:layout_marginTop="30dp"
android:textSize="18sp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
<ImageButton
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="@+id/imageButton1"
android:scaleType="fitCenter"
android:src="@mipmap/yn1"/>
<ImageButton
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="@+id/imageButton2"
android:scaleType="fitCenter"
android:src="@mipmap/yn2"/>
</LinearLayout>
<TextView
android:id="@+id/tv_info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:textSize="18sp" />
</LinearLayout>
package com.example.a4_72;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import static android.widget.Toast.LENGTH_LONG;
//采用类自身实现OnClickListener和OnKeyListener方法
public class MainActivity extends Activity implements View.OnClickListener, View.OnKeyListener {
ImageButton[] buttons=new ImageButton[2]; //定义数组来保存图片
private TextView tv_choose,tv_info;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttons[0]=(ImageButton) findViewById(R.id.imageButton1);
buttons[1]=(ImageButton) findViewById(R.id.imageButton2);
tv_choose=(TextView) findViewById(R.id.tv_choose);
tv_info=(TextView) findViewById(R.id.tv_info);
tv_choose.setText("请使用键盘中的Y、N键控制下方两个按钮");
for (ImageButton button : buttons) {
button.setOnClickListener(this);
button.setOnClickListener(this);
}
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.imageButton1:
tv_info.setText("您单击了按钮Y");
break;
case R.id.imageButton2:
tv_info.setText("您单击了按钮N");
break;
}
}
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
switch (keyCode){
case KeyEvent.KEYCODE_Y:
buttons[0].performClick();
buttons[0].requestFocus();
break;
case KeyEvent.KEYCODE_N:
buttons[1].performClick();
buttons[1].requestFocus();
break;
}
return false;
}
}