2012年3月6日星期二

Android 3.0 的列表片段(ListFragment)

列表片段(ListFragment)
- 建立新的XML文件, /res/layout/listfragment.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#101010">

<ListView android:id="@id/android:list"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"/>
<TextView android:id="@id/android:empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="No data"/>
</LinearLayout>


- 擴展ListFragment, 建立新的MyListFragment.java類.
package com.Android3ListFragment;

import android.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;

public class MyListFragment extends ListFragment {

String[] month ={
"January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December"};

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.listfragment, container, false);
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setListAdapter(new ArrayAdapter<String>(
getActivity(),
android.R.layout.simple_list_item_1,
month));
}

}


- 修改main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >

<TextView
android:layout_height="wrap_content"
android:layout_width="0px"
android:layout_weight="3"
android:text="@string/hello" />
<fragment
class="com.Android3ListFragment.MyListFragment"
android:id="@+id/mylistfragment"
android:layout_width="0px"
android:layout_weight="1"
android:layout_height="match_parent"/>

</LinearLayout>


主Activity使用自動生成的代碼便可以:
package com.Android3ListFragment;

import android.app.Activity;
import android.os.Bundle;

public class Android3ListFragmentActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}



相關文章:
- 自定義佈局的列表片段(ListFragment)

沒有留言:

發佈留言