[英]Change the Drawable position inside the button
<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 可绘制对象应更改为 android:drawableEnd="@drawable/ic_ON" 并且文本打开。
为此创建自定义布局,其中ImageView
的左侧和右侧有一个TextView
。 然后,您可以根据按钮是处于 ON 还是 OFF state,以编程方式设置左/右ImageView
的可见性。
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<View>(R.id.onOffButton)
获取对按钮的引用,并设置点击侦听器以根据 state 设置offImageView
或onImageView
的可见性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.