界面编程之基本界面组件(5)ToggleButton(状态开关按钮)
16lz
2021-12-04
ToggleButton用于切换程序中的某种状态。
ToggleButton有三个XML属性:android:checked,设置该按钮是否被选中,对应的方法为setChecked(boolean);
android:textOff,设置当按钮没有被选中时显示的文本;
android:textOn,设置当按钮没有被选中时显示的文本。
下面的例子示范动态控制布局的例子,随着按钮状态的改变,界面布局在水平和垂直布局之间切换。
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" android:orientation="vertical" tools:context=".ToggleButton" > <ToggleButton android:id="@+id/togglebutton" android:layout_width="match_parent" android:layout_height="wrap_content" android:checked="true" android:textOff="横向排列" android:textOn="纵向排列" /> <LinearLayout android:id="@+id/layout" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button 1" android:textSize="11pt" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button 1" android:textSize="11pt" /> <Button android:id="@+id/button3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button 1" android:textSize="11pt" /> </LinearLayout></LinearLayout>
Java源代码:
package com.example.togglebutton;import android.os.Bundle;import android.app.Activity;import android.view.*;import android.widget.CompoundButton;import android.widget.CompoundButton.OnCheckedChangeListener;import android.widget.LinearLayout;import android.widget.ToggleButton;public class ToggleButtonTest extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_toggle_button);ToggleButton toggleButton = (ToggleButton) findViewById(R.id.togglebutton);final LinearLayout layout = (LinearLayout) findViewById(R.id.layout);toggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {@Overridepublic void onCheckedChanged(CompoundButton arg0, boolean arg1) {// TODO Auto-generated method stubif (arg1)layout.setOrientation(1);elselayout.setOrientation(0);}});}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.activity_toggle_button, menu);return true;}}
更多相关文章
- android EditText 全面阐述
- Android(安卓)滚动条属性
- EditText使用小结
- android EditText 全面阐述
- Android(安卓)EditText 属性汇总
- html5 开发android
- Android(安卓)中文 API (25) ―― ZoomControls
- android Textview属性细节以及EditText属性
- 设置TextView文字居中