For example, send a backspace key to the edit text control to remove a character or send a char code like 112 to append a character in the edittext control programmatically.
Take a look at this article: creating-input-method.html. Basically, you can either manually send KeyEvents
or you can manually edit and commit text around the cursor
in the application's Input View
.These are all done via your IME's InputConnection
.
Hope this helps,
Check for key events in your activity. for example, this code listens for back
keypress:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK))
{
finish();
}
return super.onKeyDown(keyCode, event);
}
Your question is not all that clear, but I think you want to modify/append text to a TextView
when certain buttons are pressed. If so, you want a combination of some of the existing answers.
@Override
public void onCreate(Bundle savedInstanceState) {
...
(TextView) textView = (TextView) findViewById(R.id.myTextView);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
switch(keyCode) {
case KeyEvent.KEYCODE_BACK:
// user pressed the "BACK" key. Append "_back" to the text
textView.append("_back");
return true;
case KeyEvent.KEYCODE_DEL:
// user pressed the "BACKSPACE" key. Append "_del" to the text
textView.append("_del");
return true;
default:
return super.onKeyDown(keyCode, event);
}
}
Whether to return true
for each case you have handled (as above) or to always return super.onKeyDown(keyCode, event);
after your switch
statement will depend on your exact requirements. Check the documentation for the behaviour of onKeyDown
If, instead of appending text in each case you want to delete a character, or move the cursor, you could do that in each case
statement. Have a look at the TextView documentation for the different methods you can call. Also look at the KeyEvent documentation for a list of the keys you can check for.
if you want a click listener, the best way to do it is this:
View textfield = findViewById(R.id.textfield);
textfield .setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
/*your code for the click event here*/ }});
if you want a backspace button, do this:
public void backSpace() {
EditText textfield = (EditText)findViewById(R.id.textfield);
try {
textfield.getText().delete(textfield.getSelectionEnd() - 1, textfield.getSelectionStart());
} catch (Exception e) {
try {
textfield.getText().delete(textfield.length() - 1, textfield.length());
} catch (Exception myException) {
//textfield.getText().delete(textfield.length(), textfield.length() - 1);
}
}
}
if you want to append a character in the EditText, do this:
EditText textfield = (EditText)findViewById(R.id.textfield);
textfield.setText(textfield.getText().concat("112"));