On Android, I would like to create a button that contains some other Views. For example, something like this:
+---------------------------+
| Hello world! +-------+ |
| | image | |
| Some more info +-------+ |
+---------------------------+
But I'd like it to be more flexible than this specific example. Ideally, the button would simply be able to contain a ViewGroup, so that I could implement its layout in a separate XML file. However, because Button extends View, but not ViewGroup, this doesn't seem possible.
Is there any way to achieve this using standard Android components, or do I have to resort to writing a custom button class?
As requested, some example XML that does the trick:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:focusable="true"
android:clickable="true"
android:background="@android:drawable/btn_default">
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@android:color/primary_text_light"/>
<TextView
android:id="@+id/additional_line_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@android:color/primary_text_light"/>
<TextView
android:id="@+id/additional_line_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@android:color/primary_text_light"/>
</LinearLayout>
I had to set the colour on the TextViews explicitly, otherwise they would be nearly unreadable (they're white by default). I dug up the identifier from the SDK: .../platforms/android-7/data/res/values/public.xml
. Strangely, primary_text_light
gives black text, whereas primary_text_dark
results in white...
Create the layout of the desired button, and set it's android:background
to @android:drawable/btn_default
. Make the outermost View that contains the rest clickable
and focusable
and you're done.