【发布时间】:2012-01-30 04:41:18
【问题描述】:
我只是 changed the background of a ToggleButton,现在我希望更改随之而来的 ON/OFF 文本。最简单的方法是什么?
【问题讨论】:
标签: android togglebutton
我只是 changed the background of a ToggleButton,现在我希望更改随之而来的 ON/OFF 文本。最简单的方法是什么?
【问题讨论】:
标签: android togglebutton
您可以使用以下内容从代码中设置文本:
toggleButton.setText(textOff);
// Sets the text for when the button is first created.
toggleButton.setTextOff(textOff);
// Sets the text for when the button is not in the checked state.
toggleButton.setTextOn(textOn);
// Sets the text for when the button is in the checked state.
要使用 xml 设置文本,请使用以下命令:
android:textOff="The text for the button when it is not checked."
android:textOn="The text for the button when it is checked."
此信息来自here
【讨论】:
android.support.v7.widget.SwitchCompat 在一些我已经检查过的 OEM 上!
在您链接到的示例中,他们使用 android:textOn 和 android:textOff 将其更改为日/夜
【讨论】:
将 XML 设置为:
<ToggleButton
android:id="@+id/flashlightButton"
style="@style/Button"
android:layout_above="@+id/buttonStrobeLight"
android:layout_marginBottom="20dp"
android:onClick="onToggleClicked"
android:text="ToggleButton"
android:textOn="Light ON"
android:textOff="Light OFF" />
【讨论】:
在某些情况下,您需要强制刷新视图才能使其正常工作。
toggleButton.setTextOff(textOff);
toggleButton.requestLayout();
toggleButton.setTextOn(textOn);
toggleButton.requestLayout();
【讨论】:
requestLayout() 不起作用,但 setChecked() 起作用。
看来您不再需要 toggleButton.setTextOff(textOff);和 toggleButton.setTextOn(textOn);。每个切换状态的文本将仅通过包含相关的 xml 特征来更改。这将覆盖默认的 ON/OFF 文本。
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/toggleText"
android:textOff="ADD TEXT"
android:textOn="CLOSE TEXT"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:visibility="gone"/>
【讨论】:
您可以通过 2 个选项来做到这一点:
选项 1:通过设置其 xml 属性
`android:textOff="TEXT OFF"
android:textOn="TEXT ON"`
选项 2:以编程方式
设置onClick属性:methodNameHere(我的是toggleState) 然后写这段代码:
public void toggleState(View view) {
boolean toggle = ((ToogleButton)view).isChecked();
if (toggle){
((ToogleButton)view).setTextOn("TEXT ON");
} else {
((ToogleButton)view).setTextOff("TEXT OFF");
}
}
PS:对我有用,希望对你也有用
【讨论】: