这篇文章给大家介绍如何在Android中使用ToggleButton多状态按钮控件,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
什么是ToggleButton?
ToggleButton一般有两种状态:选中和未选中
并且需要为不同状态设置不同的文本
ToggleButton属性
android:checked=”true”——当前按钮状态,选中为”true”,未选中为”false”
android:textOn=”开”
android:checked=”true”的时候,显示 取决于checked的状态,即当checked=”true”的时候,显示textOn=”开”,当checked=”false”的时候,显示checked=”true”
具体代码
<ToggleButton
android:checked="false"
android:id="@+id/toggleButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textOn="开"
android:textOff="关" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/off" />
package com.example.admin.demo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ToggleButton;
public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
private ToggleButton tb;
private ImageView img;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 初始化控件
tb = (ToggleButton) findViewById(R.id.toggleButton);
img = (ImageView) findViewById(R.id.imageView1);
//设置监听器
tb.setOnCheckedChangeListener(this);
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
img.setImageResource(isChecked?R.drawable.on:R.drawable.off);
}
}
关于如何在Android中使用ToggleButton多状态按钮控件就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。