How can a button get focus?

There are quite a few posts affecting this topic. I thought I should ask this simple question, hoping to clarify this.

I am unable to set the focus on the button. I know that I probably missed something fundamental. Here is a simple layout:

<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical" >

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button"
    android:focusable="true" />

 </LinearLayout>

The following is simple code in onCreate ():

        Button button = (Button)findViewById(R.id.button1);
        button.setFocusable(true);
        button.requestFocus();
        button.setText("Debug");  //Just to show the code here has been executed

It just does not work (i.e. the button does not receive focus).

Any correction of my mistake or misunderstanding will be appreciated.

+15
source share
1 answer

update your code:

        Button button = (Button)findViewById(R.id.button1);
        button.setFocusable(true);
        button.setFocusableInTouchMode(true);///add this line
        button.requestFocus();
        button.setText("Debug"); 
+35
source

Source: https://habr.com/ru/post/1793904/


All Articles