[Andriod] OnKeyListener & requestFocus

  • 2730
  • 0
  • 2013-05-08

想要抓取ENTER鍵, 必須implements OnKeyListener並Override onKey, ENTER鍵的keyCode包含KEYCODE_ENTER(66)及KEYCODE_NUMPAD_ENTER(160), Soft Keyboard會回傳KEYCODE_ENTER, Scanner則會回傳KEYCODE_NUMPAD_ENTER, 兩者都必須與必須與ACTION_DOWN連用, 否則會抓不到

想要抓取ENTER鍵, 必須implements OnKeyListener並Override onKey, ENTER鍵的keyCode包含KEYCODE_ENTER(66)及KEYCODE_NUMPAD_ENTER(160), Soft Keyboard會回傳KEYCODE_ENTER, Scanner則會回傳KEYCODE_NUMPAD_ENTER, 兩者都必須與必須與ACTION_DOWN連用, 否則會抓不到


package com.example.excercise3;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.EditText;
import android.widget.TextView;
import android.view.KeyEvent;

public class Activity1 extends Activity implements OnKeyListener {
	
	private EditText etSN;
	private EditText etErrCode;
	private TextView tvMsg;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout1);
		
		etSN = (EditText)findViewById(R.id.etSN);
		etSN.setOnKeyListener(this); 
		etSN.requestFocus();
		
		etErrCode = (EditText)findViewById(R.id.etErrCode);
		etErrCode.setOnKeyListener(this); 
		
		tvMsg = (TextView)findViewById(R.id.tvMsg);
		
	}
	
	@Override 
	public boolean onKey(View view, int keyCode, KeyEvent event) {
		  if (event.getAction() == KeyEvent.ACTION_DOWN && (event.getKeyCode() ==KeyEvent.KEYCODE_NUMPAD_ENTER || event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {  	
			switch (view.getId()) {     
			case R.id.etSN:      
				tvMsg.setText("SN:" + etSN.getText()); 
				etErrCode.requestFocus();
				break;     
			case R.id.etErrCode:      
				tvMsg.setText("ErrCode:" + etErrCode.getText());
				break;     
			} 
			return true; 
		}                       
		return false; 
	}

}