android studio togglebutton

这个和switch太相似了,用toast小试牛刀:

public class MainActivity extends AppCompatActivity {
    ToggleButton toggleButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toggleButton=(ToggleButton)findViewById(R.id.toggleButton);
        toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b){
                    Toast.makeText(getApplicationContext(),"on",Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(getApplicationContext(),"off",Toast.LENGTH_SHORT).show();
                }
            }
        });

    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ToggleButtonAndroid中的一个控件,它可以用来切换两种状态,通常用于表示开关按钮。在使用ToggleButton时,你可以通过设置几个常用属性来自定义按钮的行为和外观,如android:textOn和android:textOff属性可以设置按钮在不同状态下显示的文字。 如果你想在Android Studio中使用ToggleButton,你可以参考以下步骤: 1. 在布局文件中添加ToggleButton控件,设置它的id和其他属性,如android:textOn和android:textOff。 2. 在Activity中找到ToggleButton控件,使用findViewById方法绑定该控件。 3. 为ToggleButton设置一个监听器,通过setOnCheckedChangeListener方法实现。 4. 在监听器的onCheckedChanged方法中,根据按钮的状态进行相应的操作。 以下是一个简单的示例代码,演示了如何在Android Studio中创建和使用ToggleButton控件: ```java public class MainActivity extends AppCompatActivity { private TextView tv_show = null; private ToggleButton btn_tog_test = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv_show = findViewById(R.id.tv_show); btn_tog_test = findViewById(R.id.btn_tog_test); btn_tog_test.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) { if (isChecked) { tv_show.setText("已经开始"); } else { tv_show.setText("已经停止"); } } }); } } ``` 在这个示例中,我们创建了一个Activity,并在布局文件中添加了一个TextView和一个ToggleButton控件。当ToggleButton的状态切换时,我们通过监听器来更新TextView的文本。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值