
以下的實(shí)例,實(shí)現(xiàn)點(diǎn)擊排列按鈕,實(shí)現(xiàn)三個(gè)測試按鈕布局的切換功能。
main.xml
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"android:layout_height="match_parent" tools:context=".MainActivity">
<!--定義一個(gè)ToggleButton按鈕--> <ToggleButtonandroid:id="@+id/toggle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textOff="橫向排列" android:textOn="縱向排列" android:checked="false" /> <!-- 定義一個(gè)可以動(dòng)態(tài)改變方向的線性布局--> <LinearLayoutandroid:id="@+id/test" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Button android:id="@+id/button1" android:layout_width=" wrap_content" android:layout_height="wrap_content" android:text="測試1"/> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="測試2"/> <Button android:id="@+id/button3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="測試3"/>
</LinearLayout>
</LinearLayout>
MainActivity.java
packagecom.example.togglebuttontest;
importandroid.os.Bundle;importandroid.app.Activity;importandroid.view.Menu;importandroid.widget.CompoundButton;importandroid.widget.CompoundButton.OnCheckedChangeListener;importandroid.widget.LinearLayout;importandroid.widget.ToggleButton;
public class MainActivityextends Activity {
@Overrideprotected void onCreate(BundlesavedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);ToggleButtontoggle=(ToggleButton) super.findViewById(R.id.toggle);final LinearLayouttest=(LinearLayout) super.findViewById(R.id.test);toggle.setOnCheckedChangeListener(newOnCheckedChangeListener(){
@Overridepublic voidonCheckedChanged(CompoundButton arg0, boolean arg1) {//如果選中的話if(arg1){//設(shè)置LinearLayout垂直布局,0表示水平布局test.setOrientation(0);}else{//設(shè)置LinearLayout水平布局,1表示垂直布局test.setOrientation(1);}}});}
}
愛華網(wǎng)



