繁体   English   中英

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

[英]Change the On/Off text of a toggle button Android

我只是改变了ToggleButton的背景 ,现在我想要改变它出现的ON / OFF文本。 最简单的方法是什么?

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

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

此信息来自此处

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

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

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

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

请参阅更多

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

你可以通过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:它对我有用,希望它也适合你

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

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

toggleButton.setTextOn(textOn);
toggleButton.requestLayout();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM