安卓ToggleButton的使用
2013-12-30 20:50
197 查看
以下的实例,实现点击排列按钮,实现三个测试按钮布局的切换功能。
main.xml
<LinearLayout
xmlns: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"
>
<!--定义一个ToggleButton按钮-->
<ToggleButton
android:id="@+id/toggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOff="横向排列"
android:textOn="纵向排列"
android:checked="false"
/>
<!-- 定义一个可以动态改变方向的线性布局
-->
<LinearLayout
android: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
package
com.example.togglebuttontest;
import
android.os.Bundle;
import
android.app.Activity;
import
android.view.Menu;
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);
ToggleButton
toggle=(ToggleButton) super.findViewById(R.id.toggle);
final LinearLayout
test=(LinearLayout) super.findViewById(R.id.test);
toggle.setOnCheckedChangeListener(new
OnCheckedChangeListener(){
@Override
public void
onCheckedChanged(CompoundButton arg0, boolean arg1) {
//如果选中的话
if(arg1){
//设置LinearLayout垂直布局,0表示水平布局
test.setOrientation(0);
}
else{
//设置LinearLayout水平布局,1表示垂直布局
test.setOrientation(1);
}
}
});
}
}