对android里布局文件当中的TextView对象设置事件监听,但是不响应问题解决

本文解决了在Android布局中TextView对象设置事件监听但不响应的问题。关键在于布局文件中TextView缺少`android:focusable="true"`属性,这导致无法进入按键事件方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

注意布局文件当中的第一个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>



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值