安卓课程十九 ToggleButton按钮的使用

activity_main.xml

<ToggleButton 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"
        android:id="@+id/toggleBtn"
        android:textOn="横向排列"
        android:textOff="纵向排列"
        android:checked="true" 
        />
    <LinearLayout  
        android:id="@+id/linearLayout"
        android:layout_below="@id/toggleBtn"
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >
        
        <Button android:layout_width="wrap_content" 
        android:layout_height="wrap_content"
        android:text="@string/btn"
        />
        <Button android:layout_width="wrap_content" 
        android:layout_height="wrap_content"
        android:text="@string/btn"
        />
        <Button android:layout_width="wrap_content" 
        android:layout_height="wrap_content"
        android:text="@string/btn"
        />
        
        
    </LinearLayout>

 MainActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.ToggleButton;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		final LinearLayout linearLayout = (LinearLayout) this.findViewById(R.id.linearLayout);
		ToggleButton toggleBtn = (ToggleButton) this.findViewById(R.id.toggleBtn) ;
		
		toggleBtn.setOnCheckedChangeListener(new OnCheckedChangeListener(){

			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				if(isChecked){
					//0:表示横向排列
					linearLayout.setOrientation(0);
				}else {
					//1:垂直排列
					linearLayout.setOrientation(1);
				}
			}}); 
	}
 

}

 
安卓课程十九 ToggleButton按钮的使用
 

相关推荐