Friday, April 27, 2012

Set initial focus in an android application


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?



Source: Tips4all

5 comments:

  1. 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.

    ReplyDelete
  2. Set :focusable true and call requestFocus. It does the trick.

    ReplyDelete
  3. @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 Edit Text:

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

    ReplyDelete
  4. @Someone Somewhere I used this to clear focus:

    editText.clearFocus();


    and it helps

    ReplyDelete
  5. Using code behind,

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


    that should work,

    ReplyDelete