Set initial focus in an Android application

AndroidFocus

Android Problem Overview


In my Android application it automatically focuses the first Button I have in my layout, giving it an orange outline. How can I set the initial focus preferably in XML, and can this be set to nothing?

Android Solutions


Solution 1 - Android

You could use the requestFocus tag:

<Button ...>
  <requestFocus />
</Button>

I find it odd though that it auto-focuses one of your buttons, I haven't observed that behavior in any of my views.

Solution 2 - Android

@Someone Somewhere, I tried all of the above to no avail. The fix I found is from http://www.helloandroid.com/tutorials/remove-autofocus-edittext-android . Basically, you need to create an invisible layout just above the problematic Button:

<LinearLayout android:focusable="true"
              android:focusableInTouchMode="true" 
              android:layout_width="0px"
              android:layout_height="0px" >
    <requestFocus />
</LinearLayout>

Solution 3 - Android

Set both :focusable and :focusableInTouchMode to true and call requestFocus. It does the trick.

Solution 4 - Android

I found this worked best for me.

In AndroidManifest.xml <activity> element add android:windowSoftInputMode="stateHidden"

This always hides the keyboard when entering the activity.

Solution 5 - Android

I just add this line of code into onCreate():

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

Problem solved.

Solution 6 - Android

Use the code below,

TableRow _tableRow =(TableRow)findViewById(R.id.tableRowMainBody);
tableRow.requestFocus();

that should work.

Solution 7 - Android

@Someone Somewhere I used this to clear focus:

editText.clearFocus();

and it helps

Solution 8 - Android

android:focusedByDefault="true"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionstealthcopterView Question on Stackoverflow
Solution 1 - AndroidMatthiasView Answer on Stackoverflow
Solution 2 - AndroidVince LasmariasView Answer on Stackoverflow
Solution 3 - AndroidRuivoView Answer on Stackoverflow
Solution 4 - AndroidJamesView Answer on Stackoverflow
Solution 5 - AndroidSam TangView Answer on Stackoverflow
Solution 6 - Androiduser673449View Answer on Stackoverflow
Solution 7 - AndroidRuobin WangView Answer on Stackoverflow
Solution 8 - AndroidTiyebMView Answer on Stackoverflow