Android开发控件之ToggleButton
16lz
2021-01-23
ToggleButton的使用解析
1两种状态:
选中和未选中状态,并且需要为不同的状态设置不同的显示文本
2.属性:
Android:checked=”true”
Android:textOff=”显示文本1”
Android:textOn=”显示文本2”
3.使用样例(通过ToggleButton控制ImageView显示不同的图片)
a.布局文件activity_main代码
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <ToggleButton android:id="@+id/toggleButton1" android:layout_width="match_parent" android:layout_height="wrap_content" android:checked="false" android:textOff="关" android:textOn="开" /><ImageView android:id="@+id/imageView1" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/off" /></LinearLayout>
b.MainActivity代码
public class MainActivity extends ActionBarActivity implements 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.toggleButton1); img=(ImageView) findViewById(R.id.imageView1); tb.setOnCheckedChangeListener(this); }@Overridepublic void onCheckedChanged(CompoundButton arg0, boolean isChecked) {img.setBackgroundResource(isChecked?R.drawable.on:R.drawable.off);}}
c.方法总结
setOnCheckedChangeListener ToggleButton监听事件的方法,此样例中是通过实现接口的方式去实现事件监听的。
setBackgroundResource方法改变ImageView的Background,显示不同的图片。
d.运行结果
点击开关按钮时,将在下面两个画面进行切换
更多相关文章
- Android中Failed to 。。。。。。timeout错误的解决方法
- 对android应用一些破解的方法
- (2019年10月更新) Android 最全的底部导航栏实现方法
- Android工程内嵌资源文件的两种方法
- 解决国行安卓(Android)手机无谷歌(Google)服务的一个参考方法