2012年3月10日星期六

自定義佈局的列表片段(ListFragment)

本例子示範如何在列表片段(ListFragment)中顯示自定義的佈局.

自定義佈局的列表片段(ListFragment)

創建/res/layout/row.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="wrap_content"
android:orientation="vertical">

<TextView
android:id="@+id/text1"
android:textSize="26dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/text2"
android:textSize="26dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

</LinearLayout>


修改MyListFragment.java, 創建和使用我們自定義的陣列適配器, MyCustomAdapter.
package com.Android3ListFragment;

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

public class MyListFragment extends ListFragment {

class Month{
String chinese;
String english;

Month(String c, String e){
chinese = c;
english = e;
}

public String getChinese(){
return chinese;
}
public String getEnglish(){
return english;
}
}


Month[] months ={
new Month("一月", "January"),
new Month("二月", "February"),
new Month("三月", "March"),
new Month("四月", "April"),
new Month("五月", "May"),
new Month("六月", "June"),
new Month("七月", "July"),
new Month("八月", "August"),
new Month("九月", "September"),
new Month("十月", "October"),
new Month("十一月", "November"),
new Month("十二月", "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 MyCustomAdapter(
getActivity(),
R.layout.row,
months));
}

public class MyCustomAdapter extends ArrayAdapter<Month>{

public MyCustomAdapter(Context context, int textViewResourceId,
Month[] objects) {
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater=getActivity().getLayoutInflater();
View row=inflater.inflate(R.layout.row, parent, false);
TextView text1 = (TextView)row.findViewById(R.id.text1);
TextView text2 = (TextView)row.findViewById(R.id.text2);

text1.setText(months[position].getChinese());
text2.setText(months[position].getEnglish());

return row;
}

}

}


其他文件, Android3ListFragmentActivity.java(主Activity), main.xml(主layout), listfragment.xml, 參考前文"Android 3.0 的列表片段(ListFragment)".

沒有留言:

發佈留言