现在的位置: 首页 > 综合 > 正文

从零开始学android:Android事件处理—键盘事件

2013年07月30日 ⁄ 综合 ⁄ 共 2042字 ⁄ 字号 评论关闭

键盘事件

键盘事件主要功能是用于进行键盘的监听处理操作,例如:用户输入某些内容之后,可以直接通过键盘事件进行跟踪,下面在文本框上设置键盘的操作事件,将文本框每次输入的内容直接增加到文本显示组件中,键盘事件使用View.OnKeyListener接口进行事件的处理,此接口定义如下:

public static interface View.OnKeyListener{
	public boolean onKey(View v, int keyCode, KeyEvent event) ;
}

范例

在main.xml中定义组件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    
    <TextView 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="请输入email地址:"        
        />
	<EditText 
	    android:id="@+id/input"
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"
	    android:selectAllOnFocus="true"
	    />
	<ImageView 
	    android:id="@+id/img"
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"
	    android:src="@drawable/wrong"
	    />
    
</LinearLayout>

定义Activity程序进行事件操作

package com.richard.onkeylistener;

import android.os.Bundle;
import android.app.Activity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.EditText;
import android.widget.ImageView;

public class Main extends Activity {
	private EditText input = null;
	private ImageView img = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		this.input = (EditText) super.findViewById(R.id.input);
		this.img = (ImageView) super.findViewById(R.id.img);
		this.input.setOnKeyListener(new OnKeyListenerImpl());
	}
	
	private class OnKeyListenerImpl implements OnKeyListener{

		@Override
		public boolean onKey(View v, int keyCode, KeyEvent event) {
			switch(event.getAction()){
			case KeyEvent.ACTION_UP:
				String msg = Main.this.input.getText().toString();
				if(msg.matches("\\w+@\\w+\\.\\w+")){	//判断是否是email
					Main.this.img.setImageResource(R.drawable.right);
				}else{
					Main.this.img.setImageResource(R.drawable.wrong);
				}
			case KeyEvent.ACTION_DOWN:
			default:
				break;
			}
			return false;
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

测试效果:

抱歉!评论已关闭.