2

我正在尝试更改 Android 中切换按钮上的默认 On 和 Off 文本。我知道如何在 xml 中执行此操作。我的问题是如何在代码中以编程方式实现这一点。

有人可以建议吗?非常感谢。

4

3 回答 3

3

使用ToggleButton.setTextOn(String)ToggleButton.setTextOff(String)

于 2011-09-02T12:27:55.090 回答
1

您可以在 xml 中设置打开/关闭切换按钮,如下所示

// 切换按钮的xml代码

 <ToggleButton
            android:id="@+id/toggBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_alignParentRight="true"
            android:gravity="center"
            android:textOn="On"         //when your button on by clicking "On" text will be displayed
            android:textOff="Off" />   //When you off the toggle button "Off" text will be displayed

在java代码中。

    ToggleButton toggleButton=(ToggleButton)findViewById(R.id.toggBtn);

toggleButton.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View arg0) {
                if(toggleButton.getText().toString().equals("on")){
                ////do when toggle button is on 
                }else if(toggleButton.getText().toString().equals("off")){
                // do when toggle button is off 
                }   

            }
        });
于 2011-09-02T06:41:42.150 回答
1

你可以尝试这样的事情:

ToggleButton btn = new ToggleButton(this); //this is optional and you should use your way to create the button :)
    if (btn.isChecked())
    {
        btn.setText("something");
    }
    else
    {
        btn.setText("something else");
    }

建议:您应该将此验证放在 onclickListener 中:)

于 2011-09-02T06:46:53.647 回答