Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a button get the focus?

Tags:

android

button

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

I am unable to achieve setting the focus on a button. I know I probably miss something fundamental. Here is the 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 the 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 simply does not work (i.e. the button does not get the focus).

Any correction of my error or misunderstanding will be greatly appreciated.

like image 856
Hong Avatar asked Mar 17 '12 12:03

Hong


People also ask

Can a button have focus?

To make the user aware of their interactive character, buttons have different states: init, hover, active/tap, disabled and focus.

How do I focus a button on page load?

The <button> tag in HTML is used to define the clickable button. The <button> tag is used to submit the content. The images and text content can use inside <button> tag. The <button> autofocus attribute is used to get focused button automatically after loading the web pages.

How do you set focus on a view?

If you are using java code to generate layout then you can use methods setFocusable(boolean) and setFocusableInTouchMode(boolean). You can then set the focus to a view using public method requestFocus(). The framework will handle routine focus movement in response to user input.


1 Answers

update your code:

        Button button = (Button)findViewById(R.id.button1);
        button.setFocusable(true);
        button.setFocusableInTouchMode(true);///add this line
        button.requestFocus();
        button.setText("Debug"); 
like image 198
ρяσѕρєя K Avatar answered Oct 22 '22 04:10

ρяσѕρєя K