[java] How to set focus on a view when a layout is created and displayed?

Currently, I have a layout which contains a Button, a TextView and an EditText. When the layout is displayed, the focus will be automatically put on the EditText, which will trigger the keyboard to show up on Android phone. It is not what I want. Is there any way that I can set the focus on TextView or on nothing when a layout is displayed?

This question is related to java android focus

The answer is


Focus is for selecting UI components when you are using something besides touch (ie, a d-pad, a keyboard, etc.). Any view can receive focus, though some are not focusable by default. (You can make a view focusable with setFocusable(true) and force it to be focused with requestFocus().)

However, it is important to note that when you are in touch mode, focus is disabled. So if you are using your fingers, changing the focus programmatically doesn't do anything. The exception to this is for views that receive input from an input editor. An EditText is such an example. For this special situation setFocusableInTouchMode(true) is used to let the soft keyboard know where to send input. An EditText has this setting by default. The soft keyboard will automatically pop up.

If you don't want the soft keyboard popping up automatically then you can temporarily suppress it as @abeljus noted:

InputMethodManager inputManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

When a user clicks on the EditText, it should still show the keyboard, though.

Further reading:


to change the focus make the textView in xml focusable

<TextView
            **android:focusable="true"**
            android:id="@+id/tv_id"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

and in java in on create

textView.requestFocus();

or simply hide the keyboard

public void hideKeyBoard(Activity act) {
    act.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
    InputMethodManager imm = (InputMethodManager) act.getSystemService(Context.INPUT_METHOD_SERVICE);
}

You should add this:

android:focusableInTouchMode="true"

You can start by adding android:windowSoftInputMode to your activity in AndroidManifest.xml file.

<activity android:name="YourActivity"
          android:windowSoftInputMode="stateHidden" />

This will make the keyboard to not show, but EditText is still got focus. To solve that, you can set android:focusableInTouchmode and android:focusable to true on your root view.

<LinearLayout android:orientation="vertical"
              android:focusable="true"
              android:focusableInTouchMode="true"
              ...
              >
    <EditText
         ...
       />
    <TextView
         ...
       />
    <Button
         ...
       />
</LinearLayout>

The code above will make sure that RelativeLayout is getting focus instead of EditText


The last suggestion is the correct solution. Just to repeat, first set android:focusable="true" in the layout xml file, then requestFocus() on the view in your code.


Set

 android:focusable="true"

in your <EditText/>


Set these lines to OnResume as well and make sure if focusableInTouch is set to true while you initialize your controls

<controlName>.requestFocus();

<controlName>.requestFocusFromTouch();

Set focus: The framework will handled moving focus in response to user input. To force focus to a specific view, call requestFocus()


i think a text view is not focusable. Try to set the focus on a button for example, or to set the property focusable to true.


None of the answers above works for me. The only (let's say) solution has been to change the first TextView in a disabled EditText that receives focus and then add

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

in the onCreate callback to prevent keyboard to be shown. Now my first EditText looks like a TextView but can get the initial focus, finally.


This works:

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

To set focus, delay the requestFocus() using a Handler.

private Handler mHandler= new Handler();

public class HelloAndroid extends Activity {
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.main);

     LinearLayout mainVw = (LinearLayout) findViewById(R.id.main_layout);

     LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( 
           LinearLayout.LayoutParams.FILL_PARENT,
           LinearLayout.LayoutParams.WRAP_CONTENT);

     EditText edit = new EditText(this);
     edit.setLayoutParams(params);
     mainVw.addView(edit);

     TextView titleTv = new TextView(this);
     titleTv.setText("test");
     titleTv.setLayoutParams(params);
     mainVw.addView(titleTv);

     mHandler.post(
       new Runnable() 
       {
          public void run() 
          {
            titleTv.requestFocus();
          } 
       }
     );
   }
}

Try

comp.requestFocusInWindow();

you can add an edit text of size "0 dip" as the first control in ur xml, so, that will get the focus on render.(make sure its focusable and all...)


You can try just hidding the keyboard. Something like this:

InputMethodManager inputManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to focus

How to remove focus from input field in jQuery? Set element focus in angular way Bootstrap button - remove outline on Chrome OS X How can I set focus on an element in an HTML form using JavaScript? Set Focus on EditText Mobile Safari: Javascript focus() method on inputfield only works with click? Correct way to focus an element in Selenium WebDriver using Java Prevent the keyboard from displaying on activity start What are some reasons for jquery .focus() not working? How can I set the focus (and display the keyboard) on my EditText programmatically