簡體   English   中英

如何將TextView放在ImageButton的中心?

[英]How to put a TextView in the center of a ImageButton?

說我有一個ImageButton。 我想在imagebutton上方放置一個textview,並以它為中心。 我該怎么做?

您可以通過將兩個小部件包裝在FrameLayout

例如:

<FrameLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >
    <ImageButton
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/image" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/text"
        android:layout_gravity="center" />
</FrameLayout>

您使布局過於復雜。 只需在按鈕上添加文字即可。

myImageButton.setText("text");

如果您確實想對這些視圖進行分層,則應使用RelativeLayout:

<RealtiveLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageButton 
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/img"/>           
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/app_name" 
        android:layout_centerInParent="true"/>
</RelativeLayout>

特別注意一下layout_centerInParent屬性。 這是TextView正確居中的方式。

使用常規按鈕,該按鈕仍然會擴展TextView。 然后將背景設置為圖像,並使用setText()設置文本。 您甚至可以使用drawableLeft,drawableTop等屬性在文本的上方,下方和/或左側和右側添加圖標。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM