我不想爲視圖引用資源(又名XML佈局),甚至不想使用inflater服務。如何派生BaseAdapter並自定義沒有XML的視圖?
我見過很多頁面的列表視圖示例,但每個人似乎最多從ArrayAdapter或CursorAdapter派生它們的類。
那麼,任何人都可以告訴我一個關於如何從BaseAdapter派生類並通過修改其'getView'方法來定製列表視圖的例子嗎?
我不想爲視圖引用資源(又名XML佈局),甚至不想使用inflater服務。如何派生BaseAdapter並自定義沒有XML的視圖?
我見過很多頁面的列表視圖示例,但每個人似乎最多從ArrayAdapter或CursorAdapter派生它們的類。
那麼,任何人都可以告訴我一個關於如何從BaseAdapter派生類並通過修改其'getView'方法來定製列表視圖的例子嗎?
您可以使用Java以編程方式創建視圖並設置其屬性。這與使用AWT/Swing幾乎相同,如果您熟悉這一點的話。
public class MyAdapter extends BaseAdapter {
private List<String> items; // could be an array/other structure
// using Strings as example
public MyAdapter(Context context, List<String> items) {
this.context = context;
this.items = new ArrayList<String>(items);
}
public int getCount() {
return items.size();
}
// notice I changed the return type from Object to String
public String getItem(int position) {
return items.get(position);
}
public View getView(int position, View convertView, ViewGroup parent) {
// Really dumb implementation, you should use the convertView arg if it isn't null
TextView textView = new TextView(context);
textView.setText(getItem(position);
/* call other setters on TextView */
return textView;
}
}
您可能需要重寫一些其他的方法,但他們應該是不言自明。
謝謝。我能夠在沒有XML的情況下生成列表視圖。不過,我還有另一個問題。我無法在按鈕等添加任何其他視圖到我準備的這個文本視圖上。我怎樣才能做到這一點 ?當我嘗試將佈局參數應用於我創建的新按鈕時,該應用程序崩潰。 – CodenameLambda1 2013-05-08 09:41:54
您無法將按鈕添加到「TextView」。您需要創建一個'LinearLayout'(或'ViewGroup'的某個其他子類)並添加您的視圖。您將從'getView()'返回佈局。 – Karakuri 2013-05-08 16:23:59
ArrayAdapter或CursorAdapter有什麼問題。請說明您的要求與您的慣例相違背 – CRUSADER 2013-05-08 05:59:59
ArrayAdapter的問題如上所述,我不想處理XML的一代視圖。問題,與CursorAdapter,是我不會在這裏處理SQL數據庫,因爲我需要一個簡單的實現列表。 – CodenameLambda1 2013-05-08 09:43:24