注意布局文件当中的第一个TextView当中的android:focusable="true" 原来缺少这行代码,即使在java代码中设置了事件监听,但是怎么都走不进去onkey方法当中
测试代码:测试代码,效果只是按向上向下和返回键打印出不同的东西
package com.example.testdemo;
import android.os.Bundle;
import android.app.Activity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.TextView;
public class MainActivity extends Activity implements OnKeyListener{
TextView hello_world;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
hello_world = (TextView)findViewById(R.id.hello_world);
hello_world.setOnKeyListener(this);
}
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
hello_world.setText("cccccccccccccccccccccccccccccccccccccccccccccc");
}
if (keyCode == KeyEvent.KEYCODE_DPAD_UP && event.getAction() == KeyEvent.ACTION_DOWN) {
hello_world.setText("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
return true;
}
if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN && event.getAction() == KeyEvent.ACTION_DOWN) {
hello_world.setText("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
return true;
}
return false;
}
}
注意布局文件当中的第一个TextView当中的android:focusable="true" 原来缺少这行代码,即使在java代码中设置了事件监听,但是怎么都走不进去onkey方法当中
布局文件代码:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
>
<TextView
android:id="@+id/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
android:focusable="true"/>
<TextView
android:id="@+id/abc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50sp"
android:text="@string/abc"/>
</LinearLayout>
</RelativeLayout>