当前位置:操作系统 > 安卓/Android >>

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

上一篇:http://www.zzzyk.com/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:

 \

 

补充:移动开发 , Android ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,