設定画面をイメージし、ToggleButtonを学習します。
もちろん画像を変える以外に色々できます。
プロジェクト名
プロジェクト、カンパニードメイン、パッケージネームを同じにするとコピペエラーが減ります。
Application name TestToggle
Company Domain test.com
Package name com.test.testtoggle

画像素材
* 注意 *
・画像をご自身で要するにはファイル名やファイルサイズ、拡張子に注意する必要があります。
・ファイル名は半角小文字の英数(a~z 0~9)とアンダーバー( _ )のみで、最初の1文字目は半角英字( a ~ z)のみです。
・慣れてない方はサンプル画像の使用をオススメします。


activity_main.xml(完成)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.test.testtoggle.MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="性別を選んでください" />
<ToggleButton
android:id="@+id/tb"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:checked="true"
android:textOff="女性"
android:textOn="男性" />
<ImageView
android:id="@+id/iv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/boy" />
</LinearLayout>
MainActivity.java(完成)
package com.test.testtoggle; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.ToggleButton; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ((ToggleButton)findViewById(R.id.tb)).setOnCheckedChangeListener( new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if( isChecked){ ((ImageView)findViewById(R.id.iv)).setImageResource(R.drawable.boy); }else { ((ImageView)findViewById(R.id.iv)).setImageResource(R.drawable.girl); } } } ); } }


