【Android】Segmented Radio Buttonsを使ってSegmentControlを実装する
iOSではおなじみのSegmentControlを以下のライブラリで容易に実装できたので紹介します。
vinc3m1/android-segmentedradiobutton · GitHub
SegmentControl
SegmentControlはいくつかの選択肢から一つを選んで切り替えができるUIパターンです。
以下のスライドでは用途:一連のデータを違う切り口で並べたりするとありました。
参考:スマホデザインパターン なう
リストの項目を絞り込んだりに使えるかなーと思ってます。
実装方法
Githubからライブラリをダウンロードし、プロジェクトにリンクさせます。
あとはRadioGroupを継承した「SegmentedRadioGroup.java」というクラスがあるのでRadioGroupの代わりに使用するだけ。
基本的にRadiGroupと使い方は変わらないと思います。
以下ソース
activity_main.xml
<RelativeLayout 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: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.example.segmentcontrol.MainActivity" > <com.makeramen.segmented.SegmentedRadioGroup android:id="@+id/radiogroup" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:checkedButton="@+id/radiobutton_one" android:orientation="horizontal" > <RadioButton android:id="@+id/radiobutton_one" android:layout_width="0dp" android:layout_height="30dp" android:layout_weight="1" android:button="@null" android:gravity="center" android:text="One" /> <RadioButton android:id="@+id/radiobutton_two" android:layout_width="0dp" android:layout_height="30dp" android:layout_weight="1" android:button="@null" android:gravity="center" android:text="Two" /> <RadioButton android:id="@+id/radiobutton_three" android:layout_width="0dp" android:layout_height="30dp" android:layout_weight="1" android:button="@null" android:gravity="center" android:text="Three" /> </com.makeramen.segmented.SegmentedRadioGroup> </RelativeLayout>
MainActivity.java
public class MainActivity extends ActionBarActivity implements OnCheckedChangeListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SegmentedRadioGroup radioGroup = (SegmentedRadioGroup) findViewById(R.id.radiogroup); radioGroup.setOnCheckedChangeListener(this); } @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId) { case R.id.radiobutton_one: Log.d("SegmentControl","one"); break; case R.id.radiobutton_two: Log.d("SegmentControl","two"); break; case R.id.radiobutton_three: Log.d("SegmentControl","three"); break; } } }
ライブラリを使用すれば、1から書くより大幅に時間を削減できるので積極的に使用していきたいところ。