本范例以EditView与TextView示范如何在捕捉User键盘输入文字的时实时取得文字,同步显示于Textview,实时输入输出。
package com.chaowen; import android.app.Activity; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.widget.EditText; import android.widget.TextView; public class Ex04_01 extends Activity { /** Called when the activity is first created. */ private TextView mTextView; private EditText mEditText; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mTextView=(TextView)findViewById(R.id.myTextView); mEditText=(EditText)findViewById(R.id.myEditText); //设置EditText用onkeyListener来启动 mEditText.setOnKeyListener(new EditText.OnKeyListener(){ @Override public boolean onKey(View v, int keyCode, KeyEvent event) { mTextView.setText(mEditText.getText().toString()); return false; } }); } }
//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" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <EditText android:id="@+id/myEditText" android:layout_width="149px" android:layout_height="wrap_content" android:textSize="18sp" android:layout_x="29px" android:layout_y="33px" /> <TextView android:id="@+id/myTextView" android:layout_width="135px" android:layout_height="41px" android:layout_x="33px" android:layout_y="106px" /> </LinearLayout>