Pab*_*s84 14 android button togglebutton android-layout
我想创建一个这样的Android默认值ToggleButton:
但我想在没有TEXT的情况下创建它
我尝试使用此代码:
ToggleButton tb = new ToggleButton(map);
tb.setText(null);
tb.setTextOn(null);
tb.setTextOff(null);
Run Code Online (Sandbox Code Playgroud)
但它在水平绿色条的顶部留下一个空的空间.
我不想要那个空的空间,我只想要水平的绿色条.
怎么实现呢?
谢谢
Ste*_*veR 23
顶部的空白空间是由默认的toggleButton样式中使用的2 Ninepatch(btn_toggle_off.9.png和btn_toggle_on.9.png)引起的.
要使水平条完美居中,您必须为ToggleButton创建一个新样式,它将使用两个新的9patch派生形式原始样式.
编辑:需要最少XML的方法:
为你的togglebutton创建你的两个九个补丁,命名为:my_btn_toggle_on和my_btn_toggle_off
在drawable文件夹中,创建my_btn_toggle.xml:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="false" android:drawable="@drawable/my_btn_toggle_off" />
<item android:state_checked="true" android:drawable="@drawable/my_btn_toggle_on" />
</selector>
Run Code Online (Sandbox Code Playgroud)在您的代码中,添加tb.setBackgroundResource(R.drawable.my_btn_toggle):
ToggleButton tb = new ToggleButton(map);
tb.setText(null);
tb.setTextOn(null);
tb.setTextOff(null);
tb.setBackgroundResource(R.drawable.my_btn_toggle)
Run Code Online (Sandbox Code Playgroud)RRT*_*RTW 16
只需设置以下内容:
<ToggleButton android:id="@+id/tbtn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/bg_check"
android:textOn=""
android:textOff=""
android:text="" />
Run Code Online (Sandbox Code Playgroud)
而且,风格xml,如果你需要......
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true"
android:drawable="@drawable/bg_check_on" /> <!-- pressed -->
<item android:drawable="@drawable/bg_check_off" /> <!-- default/unchecked -->
</selector>
Run Code Online (Sandbox Code Playgroud)
希望它有所帮助〜
运用
<ToggleButton
...
android:textOff="@null"
android:textOn="@null"
android:textSize="0dp" />
Run Code Online (Sandbox Code Playgroud)
不仅会使文本消失,而且还会摆脱原本会显示的空白空间.