How can I make a TextView look like a Button?

Solution 1

You should be able to just set the style in the layout XML file.

See http://developer.android.com/reference/android/R.style.html for a list of the built-in platform style. Not sure how well it would work, but its reasonably easy to do. Try this:

<TextView android:layout_height="wrap_content" style="@android:style/Widget.Button" android:layout_marginRight="5sp" android:text="" android:layout_width="fill_parent"></TextView>

EDIT: the issue is that the default button style sets the android:clickable attribute. Try and add the android:clickable attribute and set it to false:

<TextView android:layout_height="wrap_content" style="@android:style/Widget.Button" android:layout_marginRight="5sp" android:text="" android:clickable="false" android:layout_width="fill_parent"></TextView>

Solution 2

You should just be able to create a Drawable of a button and use setBackgroundDrawable() on the TextView.

Alternatively, you could use the android:background XML attribute.

Solution 3

Take this complete layout from my project:

<?xml version="1.0" encoding="utf-8"?>

<!-- Solution 1: New Button appearance -->
<!--TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    style="@android:style/Widget.DeviceDefault.Button"
    android:textAllCaps="false"
    android:focusable="false"
    android:clickable="false" /-->

<!-- Solution 2: Old Button appearance -->
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:background="@android:drawable/btn_default"
      android:gravity="center_vertical|center_horizontal" />

without clickable=false onItemClick() is not fired in ListView/GridView etc.

without focusable=false you have not the pressed button effect when you press a TextView button.

Share:
Admin
Author by

Admin

Updated on August 06, 2022

Comments

  • Admin
    Admin less than a minute

Related