liguofeng29’s blog

個人勉強用ブログだっす。

AndroidのUI - ToggleButtonとSwitch

 

activity_main.xml
 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<ToggleButton
android:id="@+id/tb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOff="ボタン縦表示"
android:textOn="ボタン横表示"
android:checked="true"/>
<Switch
android:id="@+id/sw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
/>
<LinearLayout
android:id="@+id/layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ボタン1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ボタン2"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ボタン3"/>
</LinearLayout>
</LinearLayout>
 

 

MainActivity.xml
 
package com.example.liguofeng.togglebutton_switch;

import android.location.GpsStatus;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.ToggleButton;

public class MainActivity extends AppCompatActivity {

ToggleButton tb;
Switch sw;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

tb = (ToggleButton) findViewById(R.id.tb);
sw = (Switch) findViewById(R.id.sw);
final LinearLayout layout = (LinearLayout) findViewById(R.id.layout);

// リスナー定義
CompoundButton.OnCheckedChangeListener listener = new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked) {
layout.setOrientation(LinearLayout.HORIZONTAL);
} else {
layout.setOrientation(LinearLayout.VERTICAL);
}

tb.setChecked(isChecked);
sw.setChecked(isChecked);
}
};

// Changedイベント設定
tb.setOnCheckedChangeListener(listener);
sw.setOnCheckedChangeListener(listener);
}
}