怎么在Android中实现一个开关按钮

  介绍

这篇文章将为大家详细讲解有关怎么在Android中实现一个开关按钮,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

<强>布局文件:

& lt; ? xml  version=?.0“,编码=皍tf-8" ?比;   LinearLayout & lt;   ,,xmlns: android=癶ttp://schemas.android.com/apk/res/android"   android:才能id=癅 + id/root"   android:才能layout_width=癿atch_parent"   android:才能layout_height=癿atch_parent"   android:才能取向=皏ertical"比;   & lt;才能!——定义一个ToggleButton按钮——比;   & lt; ToggleButton才能   ,,,android: id=癅 + id/toggle"   ,,,android: layout_width=皐rap_content"   ,,,android: layout_height=皐rap_content"   ,,,android: textOff=昂嵯蚺帕小?   ,,,android: textOn=白菹蚺帕小?   ,,,android:检查=皌rue"/比;   & lt;才能开关   ,,,android: id=癅 + id/switcher"   ,,,android: layout_width=皐rap_content"   ,,,android: layout_height=皐rap_content"   ,,,android: textOff=昂嵯蚺帕小?   ,,,android: textOn=白菹蚺帕小?   ,,,android:拇指=癅drawable/thumb"   ,,,android:检查=皌rue"/比;   & lt;才能!——定义一个可以动态改变方向的线性布局——比;   ,& lt; LinearLayout   ,,,android: id=癅 + id/text"   ,,,android: layout_width=癿atch_parent"   ,,,android: layout_height=癿atch_parent"   ,,,android:取向=皏ertical"比;   ,,,& lt;按钮   ,,,,,android: id=癅 + id/button01"   ,,,,,android: layout_width=皐rap_content"   ,,,,,android: layout_height=皐rap_content",/比;   ,,,& lt;按钮   ,,,,,android: id=癅 + id/button02"   ,,,,,android: layout_width=皐rap_content"   ,,,,,android: layout_height=皐rap_content",/比;   ,,,& lt;按钮   ,,,,,android: id=癅 + id/button03"   ,,,,,android: layout_width=皐rap_content"   ,,,,,android: layout_height=皐rap_content",/比;   & lt;才能/LinearLayout>   & lt;/LinearLayout>

<强>活动代码实现:

public  class  Home  extends  AppCompatActivity  {   ToggleButton 才能;toggle ;   Switch 才能;switcher ;   public 才能;void  onCreate (Bundle  savedInstanceState), {   ,,,super.onCreate (savedInstanceState);   ,,,setContentView (R.layout.activity_main);//显示manLayout   ,,,toggle =, (ToggleButton), findViewById (R.id.toggle);   ,,,switcher =,(开关),findViewById (R.id.switcher);   ,,,final  LinearLayout  text =, (LinearLayout), findViewById (R.id.text);   ,,CompoundButton.OnCheckedChangeListener  onCheckedChangeListener =,,,,,,,new  CompoundButton.OnCheckedChangeListener (), {   ,,,,@Override   ,,,,,public  void  onCheckedChanged (   ,,,,,,,,,CompoundButton  buttonView,, boolean 完成),{   ,,,,,,,if (完成),{   ,,,,,,,,,//设置LinearLayout垂直布的局   ,,,,,,,,,text.setOrientation (LinearLayout.VERTICAL);   ,,,,,,,,,toggle.setChecked(真正的);   ,,,,,,,,,switcher.setChecked(真正的);   ,,,,,,,}else  {   ,,,,,,,,,//设置水平布的局   ,,,,,,,,,text.setOrientation (LinearLayout.HORIZONTAL);   ,,,,,,,,,toggle.setChecked(假);   ,,,,,,,,,switcher.setChecked(假);   ,,,,,,,}   ,,,,,}   ,,,};   ,,,toggle.setOnCheckedChangeListener (onCheckedChangeListener);   ,,,switcher.setOnCheckedChangeListener (onCheckedChangeListener);   ,,}   null

怎么在Android中实现一个开关按钮