我写了一个自定义的view,里面用handler做了一个循环,在循环的过程中,我点击左右键怎么没有反应
我想要的结果是:循环打印 begin 和 handler, 当按下左右键是打印:Left 和 Right
我把我的工程附件上来了
请兄弟们指出原因,给出解决办法
下面是我的代码:
TestHandler 是一个activity
package cn.com.android; import android.app.Activity; import android.os.Bundle; public class TestHandler extends Activity { private ManTest test; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); test = (ManTest) findViewById(R.id.manTest); test.begin(); } }
这个是自定义View
package cn.com.android; import android.content.Context; import android.os.Handler; import android.os.Message; import android.util.AttributeSet; import android.view.KeyEvent; import android.view.View; public class ManTest extends View{ public ManTest(Context context, AttributeSet attrs) { super(context, attrs); } public ManTest(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode ==KeyEvent.KEYCODE_DPAD_LEFT){ System.out.println("KEY------> Left"); } if(keyCode ==KeyEvent.KEYCODE_DPAD_RIGHT){ System.out.println("KEY------> Right"); } return super.onKeyDown(keyCode, event); } private RefreshHandler handler = new RefreshHandler(); class RefreshHandler extends Handler { @Override public void handleMessage(Message msg) { System.out.println("Handler"); begin(); ManTest.this.invalidate(); } public void sleep(long delayMillis) { this.removeMessages(0); sendMessageDelayed(obtainMessage(0), delayMillis); } }; public void begin(){ System.out.println("Begin"); handler.sleep(1000); } }
main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <cn.com.android.ManTest android:id="@+id/manTest" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> </LinearLayout>
现在已经有解决办法了,不过感觉不应该这样子解决的!!
- @Override
- public boolean onKeyDown(int keyCode, KeyEvent event) {
- test.onKeyDown(keyCode, event);
- return super.onKeyDown(keyCode, event);
- }
- 已经把最新的代码附件了!!
@Override public boolean onKeyDown(int keyCode, KeyEvent event) { test.onKeyDown(keyCode, event); return super.onKeyDown(keyCode, event); } 已经把最新的代码附件了!!
像smaple中贪吃蛇游戏就没有在activity中重写onkeydown方法
- TMAdMob.rar (32.5 KB)
- 下载次数: 15
- TaxiCall.zip (134.7 KB)
- 下载次数: 18
- HelloMapView.zip (54.9 KB)
- 下载次数: 17
时间: 2024-09-15 09:56:56