0

我正在嘗試製作自定義切換按鈕,其中圖標比原始內置的按鈕大得多。 我想實現這樣的事情:自定義切換按鈕:如何防止文本與圖標重疊

*-------------------* 
    * *------------* * 
    * *   * * 
    * * Icon  * * 
    * *   * * 
    * *------------* * 
    * *------------* * 
    * * Text * * 
    * *------------* * 
    *-------------------* 

所以這是我的按鈕:

<ToggleButton 
      android:id="@+id/tb" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_gravity="center_horizontal" 
      android:layout_margin="18dp" 
      android:background="@drawable/custom_toggle_layer" 
      android:gravity="bottom | center_horizontal" 
      android:textAppearance="@style/CustomTBText" 
      android:textColor="@color/white" 
      android:textOff="@string/tb_off" 
      android:textOn="@string/tb_on" /> 

自定義背景在drawable/custom_toggle_layer.xml定義:

<?xml version="1.0" encoding="utf-8"?> 
    <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> 
     <item android:id="@+android:id/background" 
       android:drawable="@drawable/custom_toggle_bg" /> 
     <item android:id="@+android:id/toggle" 
       android:drawable="@drawable/custom_toggle_icon" /> 
    </layer-list> 

custom_toggle_bgcustom_toggle_icon都是選擇器,工作正常。

問題是文字與圖標底部重疊。文本對齊到底部,如果我將圖標放大,文本將正確粘貼到按鈕的底部。

我首先嚐試在切換按鈕上設置一個填充,但這只是將文本向上移動到圖標內部而已。

我想文本樣式獨立的按鈕,所以我定義自定義樣式:

<style name="CustomTBText"> 
     <item name="android:textSize">14sp</item><!-- This works --> 
     <item name="android:textColor">@color/white</item><!-- This works --> 

     <item name="android:paddingTop">15dp</item><!-- This does not work --> 
    </style> 

並試圖設置一個最高填充到只有文字,但屬性不工作(風格中的其他屬性正常工作)。

我該如何解決這個問題?我可以做一個黑客設置按鈕的文本爲空和使用外部TextView,但如果可能的話,我想使用自定義的ToggleButton來做所有事情。

回答

0

什麼自定義切換按鈕最教程做的是設置圖層列表作爲背景,以整個按鈕:

<?xml version="1.0" encoding="utf-8"?> 
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item android:id="@+android:id/background" 
      android:drawable="@drawable/custom_toggle_bg" /> 
    <item android:id="@+android:id/toggle" 
      android:drawable="@drawable/custom_toggle_icon" /> 
</layer-list> 

這會導致問題與文本(這也是爲什麼大多數教程不顯示文本)。 所以我所做的就是將custom_toggle_bg設置爲背景,並將custom_toggle_icon設置爲drawableTop,現在它可以工作。這是固定的按鈕:

<ToggleButton 
     android:id="@+id/tb" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_gravity="center_horizontal" 
     android:layout_margin="18dp" 
     android:background="@drawable/custom_toggle_bg" 
     android:drawableTop="@drawable/custom_toggle_icon" 
     android:gravity="bottom | center_horizontal" 
     android:textAppearance="@style/CustomTBText" 
     android:textColor="@color/white" 
     android:textOff="@string/tb_off" 
     android:textOn="@string/tb_on" /> 
0

您可以使用繪製的位置,像drawableLeft,drawableTop,drawabeRight,drawableBottom和drawableStart取決於是你想看到的圖標。

商祺!