瘋狂 Android 講義, 4/e – ToggleButton按钮/Switch按钮(動態改變LayOut布局)範例 P96~P98
瘋狂 Android 講義, 4/e – ToggleButton按钮/Switch按钮(動態改變LayOut布局)範例 P96~P98
資料來源:
https://github.com/daichangya/book/tree/master/android
https://pan.baidu.com/s/1d_xYJI0UQ_1tQzSj_V_NIg 提取码:70ch
XML Code
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <!-- 定义一个ToggleButton按钮 --> <ToggleButton android:id="@+id/toggle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textOff="横向排列" android:textOn="纵向排列" android:checked="true"/> <Switch android:id="@+id/switcher" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textOff="横向排列" android:textOn="纵向排列" android:thumb="@drawable/check" android:checked="true"/> <!-- 定义一个可以动态改变方向的线性布局 --> <LinearLayout android:id="@+id/test" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <!-- 下面省略了三个按钮的定义 --> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="测试按钮一" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="测试按钮二" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="测试按钮三" /> </LinearLayout> </LinearLayout>
Java Code
package org.crazyit.ui; import android.app.Activity; import android.os.Bundle; import android.widget.CompoundButton; import android.widget.LinearLayout; import android.widget.Switch; import android.widget.ToggleButton; /** * Description:<br> * 网站: <a href="http://www.crazyit.org">疯狂Java联盟</a><br> * Copyright (C), 2001-2020, Yeeku.H.Lee<br> * This program is protected by copyright laws.<br> * Program Name:<br> * Date:<br> * * @author Yeeku.H.Lee kongyeeku@163.com<br> * @version 1.0 */ public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ToggleButton toggle = findViewById(R.id.toggle); Switch switcher = findViewById(R.id.switcher); LinearLayout test = findViewById(R.id.test); CompoundButton.OnCheckedChangeListener listener = (button, isChecked) -> { if (isChecked) { // 设置LinearLayout垂直布局 test.setOrientation(LinearLayout.VERTICAL); toggle.setChecked(true); switcher.setChecked(true); } else { // 设置LinearLayout水平布局 test.setOrientation(LinearLayout.HORIZONTAL); toggle.setChecked(false); switcher.setChecked(false); } }; toggle.setOnCheckedChangeListener(listener); switcher.setOnCheckedChangeListener(listener); } }