Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Style a Button to look like an EditText (but still behave like a Button)

I realize this is sort of a weird thing to be doing, but I have a button that needs to look like an EditText but still behave like a button. My layout XML currently looks like this:

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    style="?android:attr/editTextStyle" />

That gives it the appearance of an EditText, but also messes with the behavior a little bit by preventing the onClick event from being fired unless the button has focus (effectively making it require two clicks). Is there any way to keep the style without changing the button's behavior?

I thought about just making a nine-patch background that looks like an EditText, but with so many different Android versions and skins out there I'd rather use the system style if it's possible.

like image 843
chefgon Avatar asked Nov 28 '11 22:11

chefgon


2 Answers

How about an EditText that behaves like a button?

<EditText android:id="@+id/Edit"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:clickable="true"/>

You can define an OnClickListener for it too. And it won't get focus.

like image 138
Zsombor Erdődy-Nagy Avatar answered Oct 02 '22 20:10

Zsombor Erdődy-Nagy


If it absolutely needs to be a button, you can add a focus listener to your button that fires the onclick when the button receives focus.

weirdoButton.setOnFocusChangeListener(new OnFocusChangeListener() {

  @Override
  public void onFocusChange(View view, boolean hasFocus) {
    if(hasFocus) {
      weirdoButton.performClick();
    }
  }
});

The downside is that the click will fire when the button receives focus via a trackball or d-pad. Make it un-focus-able in the layout file:

<Button
    android:id="@+id/weirdoButton"
    android:layout_width="match_parent"
    android:layout_height="50dip"
    android:focusable="false"
    style="?android:attr/editTextStyle" />
like image 44
Krylez Avatar answered Oct 02 '22 19:10

Krylez