ToggleButton控件和Button控件的功能基本相同,ToggleButton控件提供了可以表示“开/关”状态的功能。可以在wifi或者手电筒等应用使用。
一、建立工程,如图
二、activity_main.xml中代码
<?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:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/togglebutton" android:checked="true" android:textOn="纵向排列" android:textOff="横向排列" /> <LinearLayout android:id="@+id/mylayout" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="button1" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="button2" /> <Button android:id="@+id/button3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="button3" /> </LinearLayout> </LinearLayout>
三、MainActivity.java中代码
package com.study.mytoggle; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.widget.CompoundButton; import android.widget.LinearLayout; import android.widget.ToggleButton; public class MainActivity extends Activity { private ToggleButton toggleButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toggleButton = (ToggleButton)this.findViewById(R.id.togglebutton); final LinearLayout linearLayout = (LinearLayout)this.findViewById(R.id.mylayout); toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked){ linearLayout.setOrientation(1);//表示设置垂直布局 }else{ linearLayout.setOrientation(0);//表示设置水平布局 } } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
四、效果图