Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: force keyboard to appear and focus on EditText

Thanks in advance for the help.

I would like a keyboard to appear at the end or during the execution of the following code.

    // edit text
    EditText editText = new EditText(activity);
    editText.setBackgroundColor(Color.WHITE);
    editText.setGravity(Gravity.TOP);
    editText.setText("Type here...");

    RelativeLayout relativeLayoutEditText = new RelativeLayout(activity);
    RelativeLayout.LayoutParams paramRelativeLayoutEditText = new RelativeLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT, 43 * display.getHeight() / 80 );
    paramRelativeLayoutEditText.addRule(RelativeLayout.ALIGN_PARENT_TOP);
    relativeLayoutEditText.addView(editText,paramRelativeLayoutEditText);

    // add all created views to rootView
    rootView.addView(relativeLayoutEditText, paramEditText);

    // open keyboard
    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);

but the keyboard only appears after touching the editText field (ie with my finger). Is there a way that I can make the board automatically appear without using a physical touch?

As an aside I know that how I am specifying the width and height isn't exactly the right way to do things.

like image 990
HXSP1947 Avatar asked Aug 26 '15 08:08

HXSP1947


1 Answers

Add

    editText.requestFocus();

Try this:

EditText editText = (EditText ) findViewById(R.id.myTextViewId);
editText.requestFocus();
InputMethodManager imm = (InputMethodManager)   getSystemService(Context.INPUT_METHOD_SERVICE); 
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);

ensure that the edittext is focusable in touch mode. You can do it two way.

In xml:

 android:focusableInTouchMode="true"

in Java:

editText.setFocusableInTouchMode(true);
like image 168
sasikumar Avatar answered Dec 09 '22 21:12

sasikumar