【问题标题】:Change the Drawable position inside the button更改按钮内的 Drawable 位置
【发布时间】:2023-01-30 21:10:28
【问题描述】:
<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="32px"
    android:layout_marginTop="32px"
    android:layout_marginRight="32px"
    android:background="#44C4C5"
    android:drawableEnd="@drawable/ic_ON"
    android:gravity="center"
    android:text="ON"
    android:textFontWeight="300"
    android:textSize="32px"></Button>

如果按钮关闭,android drawable 应更改为 android:drawableLeft= "@drawable/ic_Off" 并且文本为 OFF。 如果按钮打开,android drawable 应该更改为 android:drawableEnd="@drawable/ic_ON" 并且文本打开。

【问题讨论】:

  • 如果你想要这样,那么不要使用按钮而是创建布局并有条件地打开或关闭它。

标签: android button


【解决方案1】:

为此创建一个自定义布局,TextView 的左右两侧有一个ImageView。然后,您可以根据按钮是处于 ON 还是 OFF 状态,以编程方式设置左/右 ImageViews 的可见性。

on_off_button.xml:

<?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="horizontal"
    android:background="#44C4C5">

    <ImageView
        android:id="@+id/offImageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_OFF"/>

    <TextView
        android:id="@+id/onOffTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ON"
        android:textFontWeight="300"
        android:textSize="32sp"/>

    <ImageView
        android:id="@+id/onImageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_ON"/>

</LinearLayout>

在您希望按钮所在的布局文件中:

    ...
    
    <include
        android:id="@+id/onOffButton"
        layout="@layout/on_off_button"/>

    ...

在您的活动或片段中,您需要使用 findViewById&lt;View&gt;(R.id.onOffButton) 获取对按钮的引用,并设置点击侦听器以根据状态设置 offImageViewonImageView 的可见性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    • 2018-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多