Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

android - How to have Image and Text Center within a Button

I want to display TEXT and Icon on a Button.

+----------------------------+
|          Icon TEXT         |
+----------------------------+

I tried with

<Button 
      android:id="@+id/Button01" 
      android:layout_width="fill_parent"
      android:layout_height="wrap_content" 
      android:paddingLeft="40dip"
      android:text="TEXT"
      android:drawableLeft="@drawable/Icon" />

But Text and Icon is not in center.
My Text size varies, according to text size Icon and Text should get adjusted to center.

How should i do it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can fake it by making a more complex layout, but I'm not sure whether it's worth it. Here's something I hacked together:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
<Button
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:layout_alignTop="@+id/foreground"
    android:layout_alignBottom="@id/foreground"
    android:layout_alignRight="@id/foreground"
    android:layout_alignLeft="@id/foreground"
    android:onClick="clickedMe" />
   <RelativeLayout
        android:id="@id/foreground"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
    <TextView  
        android:id="@+id/button_text"
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" 
        android:text="@string/hello" />
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_toLeftOf="@id/button_text"
        android:paddingTop="10dip"
        android:paddingBottom="10dip"
        android:src="@drawable/icon" />
</RelativeLayout>
</RelativeLayout>

There might be a more concise way to do it. I tend to struggle getting RelativeLayout to do what I want sometimes. Note that you need to pay attention to the z-order (Button needs to appear first in the top level RelativeLayout) and you might need to adjust padding to get it to look the way you want.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...