更改切换按钮Android的开/关文本

sty*_*972 76 android togglebutton

我只是改变了a的背景ToggleButton,现在我正在寻找改变它出现的ON/OFF文本.最简单的方法是什么?

rfs*_*010 190

您可以使用以下命令设置代码中的文本:

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.
Run Code Online (Sandbox Code Playgroud)

要使用xml设置文本,请使用以下命令:

android:textOff="The text for the button when it is not checked."
android:textOn="The text for the button when it is checked." 
Run Code Online (Sandbox Code Playgroud)

此信息来自此处

  • 但它不适用于ei samsung和HTC手机 (4认同)
  • 以编程方式更新打开和关闭文本时,按钮不会使用新文本重绘自身.您可以通过调用setChecked(toggleButton.isChecked)强制重绘.听起来很荒谬,但这是一个强迫重绘的黑客行为.请参阅[此stackoverflow答案](http://stackoverflow.com/a/3792554/2590478). (4认同)
  • Serafins,那不对.它适用于三星和HTC手机. (2认同)

Mar*_*k B 16

在您链接到的示例中,他们使用android:textOn和将其更改为日/夜android:textOff


Joo*_*lah 9

将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" />
Run Code Online (Sandbox Code Playgroud)