OnKeyListener: Interface definition for a callback to be
invoked when a hardware key event is dispatched to this view. The callback will
be invoked before the key event is given to the view. This is only useful for
hardware keyboards; a software input method has no obligation to trigger this
listener.
onKey (View v, int
keyCode, KeyEvent event) :Called when a hardware key is dispatched to
a view. This allows listeners to get a chance to respond before the target
view.
keyCode: The code for the physical key that was pressed.
event: The KeyEvent object containing full information about
the event.
MainActivity.java:
public class MainActivity extends Activity {
EditText
et;
@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText)
findViewById(R.id.editText1);
et.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent
event) {
if(keyCode == KeyEvent.KEYCODE_ENTER &&
event.getAction() == KeyEvent.ACTION_DOWN){
Toast.makeText(MainActivity.this, "Welcome
"+et.getText().toString()
+"!", Toast.LENGTH_SHORT).show();
}
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;
}
}
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="38dp"
android:ems="10" />
</RelativeLayout>
No comments:
Post a Comment