Android simulate button press
I am trying to execute an e开发者_开发技巧vent mouse press within my android application. When the user enters a CARRIAGE RETURN when entering text into a text field. I would like to execute a mouse button press on an ADD button when that character is detected in my OnClickListener for that EditText ui.
Peter -
It sounds like what you want to do is override the EditorAction for the given EditText, and then programmatically perform the same action as the OnClickListener. For example:
EditText inputText; //This is either created in code or inflated via XML
Button addButton; //This is either created in code or inflated via XML
inputText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
addButton.performClick();
//Tell the system you consumed the action event
return true;
}
});
The actionId can be a useful property too, as it reports the specific action (DONE, NEXT, etc.) based on the soft keyboard method shown...but keep in mind that if the user presses enter from a hardware keyboard the action will ALWAYS be EditorInfo.IME_NULL
, so it may not serve your purpose to monitor this value.
This is a safer method than overriding KeyEvent listeners, as you run less risk of consuming events you don't want and didn't know you stole.
Hope that helps!
精彩评论