這很簡單,你只需要擴展ArrayAdapter。我ArrayAdapter做兩分不同的事情:
- 強似一個RESOURCEID,我的適配器採取ResourceIds
陣列
- getView()檢查位置並加載相應的資源
這是一個微不足道的例。如果你打算使它比前半部分看起來更復雜,而後半部分不同,那麼你應該覆蓋getViewTypeCount()和getItemViewType()。
工作例如:
public class Example extends Activity {
public class MyArrayAdapter<T> extends ArrayAdapter<T> {
LayoutInflater mInflater;
int[] mLayoutResourceIds;
public MyArrayAdapter(Context context, int[] textViewResourceId, List<T> objects) {
super(context, textViewResourceId[0], objects);
mInflater = (LayoutInflater)context.getSystemService (Context.LAYOUT_INFLATER_SERVICE);
mLayoutResourceIds = textViewResourceId;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null && position > 2)
convertView = mInflater.inflate(mLayoutResourceIds[1], parent, false);
return super.getView(position, convertView, parent);
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] array = new String[] {"one", "two", "three", "four", "five", "six"};
List<String> list = new ArrayList<String>();
Collections.addAll(list, array);
ListView listView = new ListView(this);
listView.setAdapter(new MyArrayAdapter<String>(this, new int[] {android.R.layout.simple_list_item_1, android.R.layout.simple_list_item_single_choice}, list));
setContentView(listView);
}
}
來源
2012-08-02 23:05:09
Sam
可能重複:http://stackoverflow.com/questions/4777272/android-listview-with-different-layout-for-each-row – Ixx 2012-08-02 22:36:08