Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Button with custom XML layout

Is it possible to create a button with a custom xml layout?

I have this layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:padding="1dp"
  android:background="#7e7e7e">

 <RelativeLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:padding="10dp"
   android:background="#f9f9f9">

 <TextView
  android:id="@+id/TextView01" 
  android:layout_width="wrap_content" 
  android:layout_height="wrap_content"
  android:layout_alignParentLeft="true"
  android:text="ButtText"
  android:textColor="#000000">
 </TextView>

 <ImageView 
  android:id="@+id/ImageView01" 
  android:layout_width="wrap_content" 
  android:layout_height="wrap_content" 
  android:background="@drawable/arrow"
  android:layout_alignParentRight="true">
 </ImageView>

 </RelativeLayout>
</LinearLayout>

Now I want to use this on a button. Anyone know how I can do this?
I was thinking if I had Button.java file that extended Button. And then setView(R.layout.mylayout.xml); ... but that was to easy, and it clearly not working

Regards Martin

like image 814
f0rz Avatar asked Feb 25 '10 12:02

f0rz


2 Answers

I've been dealing with this recently because I wanted to put two textviews in a button. You have to choose:

  1. Extend Button class and use it in your layout
  2. Use a Layout insted of a button and drag inside everithing you need and make it clickable by adding this parametter to it:

    android:clickable="true"
    

After that you can modify te apperance of your layout by defining the

android:background="@drawable/my_background"

to give to it a "button-like" face and behavior

/res/drawable/mi_background.xml

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android">   
    <item android:state_focused="true" android:drawable="@color/black"/> 
    <item android:state_pressed="true" android:state_enabled="false" android:drawable="@color/black" />
    <item android:drawable="@color/white"/> 
 </selector>
like image 195
dinigo Avatar answered Oct 20 '22 00:10

dinigo


You cannot literally use that layout on the face of a Button. You can achieve a similar look using the android:drawableRight property on a Button, though.

like image 44
CommonsWare Avatar answered Oct 20 '22 01:10

CommonsWare