2012年11月13日火曜日

[Android SDK] 設定画面のレイアウトをカスタマイズする

Androidアプリには設定画面がつきものです。標準で設定画面を作るためのクラス(PreferenceActivity)が用意されており、XMLで設定項目を記述するだけで簡単に作れる。

ただ、設定画面のレイアウトをカスタマイズするには特殊なやり方が必要になります。

PreferenceActivityを継承してActivityを作るのは同じですが、setContentViewメソッドでレイアウトファイル(XML)を指定するところがポイント。
public class RpNotePreferenceActivity extends PreferenceActivity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.act_preference);
    addPreferencesFromResource(R.xml.preference);
  }
}

単純にレイアウトファイル(XML)を作成するだけではダメで、設定画面に置き換えるListViewを「android:id="@android:id/list"」属性付きで追加する必要があります。
簡単な例ですと次のようにすると、
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    tools:context=".activity.RpNotePreferenceActivity" >

    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1" />
 <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal">
  <Button
      android:id="@+id/button1"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:text="Button" />
    </LinearLayout>
</LinearLayout>

こんな感じで、画面下側にボタンがあるような設定画面が作れます(実際には、リストが設定項目に置き換わります)。

試してみてください。

0 件のコメント:

コメントを投稿