Kah – The Developer

Changing Button Text in Android

Posted by: kahgoh on: 29 June, 2008

Code has been updated on 19 Aug 2008 to work with 0.9 beta

Lets say you have an Android (if you don’t know what Android is, have a look at the Android website) view with two buttons, like this view:


 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:orientation="vertical"
 4     android:layout_width="fill_parent"
 5     android:layout_height="fill_parent"
 6     android:id="@+id/backgroundView">
 7    <Button android:id="@+id/testButton"
 8         android:text="@string/buttonText"
 9         android:layout_width="wrap_content"
10         android:layout_height="wrap_content" />
11    <Button android:id="@+id/fakeButton"
12         android:layout_width="wrap_content"
13         android:layout_height="wrap_content"
14         android:text="Fake" />
15 </LinearLayout>

Like in Swing, to capture focus and clicking events on the first button, you first create a listener that implements the Button.OnClickListener and Button.OnFocusChangeListener. The button’s text can be changed by calling the setText() method on the button. For example, to change the text when the focus is changed and when it is clicked:


 1  private class ButtonAction implements 
 2      Button.OnClickListener,
 3      Button.OnFocusChangeListener
 4  {
 5      @Override
 6      public void onClick(View arg0) 
 7      {
 8          counter++;
 9          testButton.setText("Times clicked: " 
10                  + Integer.toString(counter));
11      }
12
13      @Override
14      public void onFocusChange(View arg0,
15              boolean isFocused) 
16      {
17          if (isFocused == true)
18          {
19              testButton.setText("Now click!");
20          }
21          else
22          {
23              testButton.setText("Out of focus!");
24          }
25      }
26  }

Of course, you have to also add the listener to button! This is also fairly easy to do in Android:

 1    /** Called when the activity is first created. */
 2    @Override
 3    public void onCreate(Bundle icicle) 
 4    {
 5      super.onCreate(icicle);
 6      setContentView(R.layout.main);
 7      
 8      ButtonAction testListener = new ButtonAction();
 9        testButton = (Button) findViewById(R.id.testButton);
10        testButton.setOnClickListener(testListener);
11        testButton.setOnFocusChangeListener(testListener);
12        findViewById(R.id.backgroundView);
13    }
14

Tags:

1 Response to "Changing Button Text in Android"

[...] Progress Bar After A Dialog In Android In a previous post, I showed how to add listeners to buttons so that you can modify its text when its in focus or it [...]

Leave a Reply