Android – new line, shmew line
Filed Under (android, java, programming | ) by Nathan Schwermann on 26-01-2010
Tagged Under : android, java, programming
In a previous blog post I talked about how to avoid having your users make a new line when the press enter on an EditText view in your Android applications. It was a hack way where you had to make your own EditText class and override onKeyDown. It works just fine but since then I have found a much easier way to achieve the same goal.
First your activity or dialog needs to implement OnEditorActionListener, set the onEditorActionListener in onCreate and…. thats it!!!! Right out of the box the implemented method automatically cancels sends a null character instead of a new line character when you press enter.
public class AdjustStringDialog extends Dialog implements android.view.View.OnClickListener, OnEditorActionListener{
private EditText editTextView;
public AdjustStringDialog(Context context, UnderlinedView mV) {
super(context);
setTitle("My Dialog Box");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.adjuststring);
retisterViews();
editTextView.setOnEditorActionListener(this);
}
private void retisterViews() {
editTextView = (EditText)findViewById(R.id.editString);
findViewById(R.id.finishedAdjustString).setOnClickListener(this);
}
@Override
public void onClick(View v) {
closeDialog();
}
private void closeDialog() {
//do what you want with the entered text
dismiss();
//update UI with new text if needed
}
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
closeDialog();
return false;
}
}
Of course you can detect any key that is being pressed aside from the enter key with the event argument, and you can handle cases like the ‘Next’ button with actionId as well. Know any other ways to accomplish this, or care to share something you implemented with onEditorAction feel free to comment!
Cheers and happy 2010!

