I wrote a custom view, which uses handler for a loop. in the loop process, how can I click the Left or Right key to make a response?
The result I want is: Print begin and handler cyclically. When the left and right keys are pressed, print: left and right.
I have attached my project.
Ask the brothers to point out the cause and give a solution
The following is my code:
Testhandler is an 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(); }}
This is a custom 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);}@Overridepublic 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>
Now there is a solution, but it doesn't feel like this !! Java code
- @ Override
- Public Boolean onkeydown (INT keycode, keyevent event ){
- Test. onkeydown (keycode, event );
- Return super. onkeydown (keycode, event );
- }
- The latest code has been added !!
@ Overridepublic Boolean onkeydown (INT keycode, keyevent event) {test. onkeydown (keycode, event); return Super. onkeydown (keycode, event);} has added the latest code !!
A snake game like smaple does not overwrite the onkeydown method in the activity.
- Tmadmob.rar (32.5 KB)
- Downloads: 15
- Taxicall.zip (134.7 KB)
- Downloads: 18
- Hellomapview.zip (54.9 KB)
- Downloads: 17