更新时间:2022-09-06 10:08:18
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(); } }
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); } }
<?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); } 已经把最新的代码附件了!!