keyboard event OnKeyListener

1. Rendering: Just enter A in the text box, A will be displayed, and B will be displayed....

(1)activity_main.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     xmlns:tools="http://schemas.android.com/tools"
 4     android:layout_width="match_parent"
 5     android:layout_height="match_parent"
 6     android:paddingBottom="@dimen/activity_vertical_margin"
 7     android:paddingLeft="@dimen/activity_horizontal_margin"
 8     android:paddingRight="@dimen/activity_horizontal_margin"
 9     android:paddingTop="@dimen/activity_vertical_margin"
10     tools:context="com.example.app3.MainActivity"
11     android:orientation="vertical">
12 
13     <EditText
14         android:id="@+id/et"
15         android:layout_width="match_parent"
16         android:layout_height="wrap_content" />
17     <TextView
18         android:id="@+id/tv_show"
19         android:layout_width="wrap_content"
20         android:layout_height="wrap_content"
21         android:text="" />
22 </LinearLayout>
View Code

 (2)MainAcivity.java

 1 package com.example.app3;
 2 
 3 import android.content.DialogInterface;
 4 import android.support.v7.app.AppCompatActivity;
 5 import android.os.Bundle;
 6 import android.view.KeyEvent;
 7 import android.view.View;
 8 import android.widget.EditText;
 9 import android.widget.TextView;
10 
11 public class MainActivity extends AppCompatActivity {
12     private EditText editText;
13     private TextView textView;
14 
15     @Override
16     protected void onCreate(Bundle savedInstanceState) {
17         super.onCreate(savedInstanceState);
18         setContentView(R.layout.activity_main);
19 
20         editText = (EditText) findViewById(R.id.et);
21         textView = (TextView) findViewById(R.id.tv_show);
22 
23         editText.setOnKeyListener(new View.OnKeyListener() {
24             @Override
25             public boolean onKey(View v, intkeyCode, KeyEvent event) { //Note the change of parameters here
 26                  switch (event.getKeyCode()){
 27                      case KeyEvent.KEYCODE_A:
 28                          textView.setText("Clicked on A" );
 29                          break ;
 30                      case KeyEvent.KEYCODE_B:
 31                          textView.setText("Clicked on B" );
 32                          break ;
 33                      case KeyEvent.KEYCODE_C:
 34                          textView.setText("Clicked on C" );
 35                          break ;
 36                  }
 37                  return  false;
38             }
39         });
40 
41     }
42 }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325698207&siteId=291194637