Android ApiDemos示例解析(171):Views->Lists->4. ListAdapter

上一篇:/kf/201209/156201.html
本例返回一自定義View -SpeechView. 這個View由兩個TextView構成,一個TextView顯示Title,一個View顯示內容:其構造函數定義如下:

[java] 
public SpeechView(Context context, String title, String words) { 
 super(context); 
 
 this.setOrientation(VERTICAL); 
 
 // Here we build the child views in code. They could also have  
 // been specified in an XML file.  
 
 mTitle = new TextView(context); 
 mTitle.setText(title); 
 addView(mTitle, new LinearLayout.LayoutParams( 
 LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); 
 
 mDialogue = new TextView(context); 
 mDialogue.setText(words); 
 addView(mDialogue, new LinearLayout.LayoutParams( 
 LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); 

public SpeechView(Context context, String title, String words) {
 super(context);

 this.setOrientation(VERTICAL);

 // Here we build the child views in code. They could also have
 // been specified in an XML file.

 mTitle = new TextView(context);
 mTitle.setText(title);
 addView(mTitle, new LinearLayout.LayoutParams(
 LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

 mDialogue = new TextView(context);
 mDialogue.setText(words);
 addView(mDialogue, new LinearLayout.LayoutParams(
 LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
}

自定義的SpeechListAdapter 的getView定義如下:

 

[java] 
public View getView(int position, View convertView, 
 ViewGroup parent) { 
 SpeechView sv; 
 if (convertView == null) { 
 sv = new SpeechView(mContext, mTitles[position], 
 mDialogue[position]); 
 } else { 
 sv = (SpeechView) convertView; 
 sv.setTitle(mTitles[position]); 
 sv.setDialogue(mDialogue[position]); 
 } 
 
 return sv; 

public View getView(int position, View convertView,
 ViewGroup parent) {
 SpeechView sv;
 if (convertView == null) {
 sv = new SpeechView(mContext, mTitles[position],
 mDialogue[position]);
 } else {
 sv = (SpeechView) convertView;
 sv.setTitle(mTitles[position]);
 sv.setDialogue(mDialogue[position]);
 }

 return sv;
}

 

因此列表的每項都顯示為一個SpeechView:

 

 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *