だいぶ寒くなってきました。
そんな寒さにも負けず、Androidの開発の練習ちっくなことをやっとります。
なんか動的に扱う場合はListViewよりもListFragmentの方が使いやすいようなので、ちょっと使ってみることに。
参考というか、ほとんど丸パクリだけれど、
ListFragment の基本的な使い方 - Android 開発入門を見ながら、
以下のように書いて実行してみました。
src/com.example.listfragment/MainActivity.java
package com.example.listFragmentTest;
import com.example.listFragmentTest.R;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
res/layout/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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<fragment
android:id="@+id/list_parent"
class="com.example.listFragmentTest.ItemListFragment"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent"/>
</LinearLayout>
src/com.example.listfragment/ItemListFragment.java
package com.example.listFragmentTest;
import com.example.listFragmentTest.R;
import android.app.ListFragment;
import android.os.Bundle;
import android.widget.ArrayAdapter;
public class ItemListFragment extends ListFragment {
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayAdapter adapter =
ArrayAdapter.createFromResource(
getActivity(),
R.array.list,
android.R.layout.simple_list_item_1);
setListAdapter(adapter);
}
}
res/layout/layout_list.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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<fragment
android:id="@+id/list_child"
class="com.example.listFragmentTest.ItemListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
res/values/styles.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">listFragmentTest</string>
<string name="action_settings">Settings</string>
<string-array name="list">
<item >a</item>
<item >b</item>
<item >c</item>
<item >d</item>
</string-array>
</resources>
で、様子は下の感じ。