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

问题描述 投票:73回答:7

我只是changed the background of a ToggleButton,现在我想改变它出现的ON / OFF文本。最简单的方法是什么?

android togglebutton
7个回答
186
投票

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

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


16
投票

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


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" />

2
投票

看来你不再需要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
投票

是的,您可以更改开/关按钮

    android:textOn="Light ON"
    android:textOff="Light OFF"

请参阅更多

http://androidcoding.in/2016/09/11/android-tutorial-toggle-button


1
投票

你可以通过2个选项来做到这一点:

选项1:通过设置其xml属性

 `android:textOff="TEXT OFF"
  android:textOn="TEXT ON"`

选项2:以编程方式

设置属性onClick:methodNameHere(mine is 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:它对我有用,希望它也适合你


1
投票

在某些情况下,您需要强制刷新视图才能使其正常工作。

toggleButton.setTextOff(textOff);
toggleButton.requestLayout();

toggleButton.setTextOn(textOn);
toggleButton.requestLayout();
© www.soinside.com 2019 - 2024. All rights reserved.