How to validate keys on the virtual keyboard on Android?
I want to have a toast message to display "Enter numeric characters only" w开发者_如何转开发henever the user presses a non-numeric key on the virtual keyboard. Any clue?
You could set up a TextWatcher and process every character using the onTextChanged() event while the user types and ignore the unwanted characters as the user types.
Its not good UI design to keep popping up messages to the user on every keystroke, instead you could just let them know in the tutorial or introduction.
or use android:inputType="number" in your xml file. This will make it so that you can only enter numbers. See "Input Method Framework" in Mark Murphy's book, or search on the developer site.
As there isn't an event available for the virtual keyboard, i have found a way around to validate the keys by using the TextChanged event, Here's how i did it:
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class ShowKeypad extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
EditText emailTxt = (EditText) findViewById(R.id.editText);
emailTxt.addTextChangedListener(new TextWatcher()
{
public void afterTextChanged (Editable s){
Log.d("seachScreen", "afterTextChanged");
}
public void beforeTextChanged (CharSequence s, int start, int
count, int after)
{
Log.d("seachScreen", "beforeTextChanged");
}
public void onTextChanged (CharSequence s, int start, int before,
int count)
{
Log.d("seachScreen", s.toString());
}
final TextView tv = (TextView)findViewById(R.id.tv);
/*emailTxt.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
//Log.i("Key Value", String.valueOf(keyCode));
//Toast.makeText(ShowKeypad.this, String.valueOf(keyCode), Toast.LENGTH_SHORT);
Log.i("Key Value:", String.valueOf(keyCode));
return true;
}; });*/
});
}
}
Is there any better way to validate? Please give your feedback.
精彩评论