你可以做类似的事情
public View getView(int position, View convertView, ViewGroup parent)
{
// Create a linear layout to hold other views
LinearLayout oItemViewLayout = new LinearLayout(mContext);
// ImageView
ImageView i = new ImageView(mContext);
i.setImageResource(mImageIds[position]);
i.setScaleType(ImageView.ScaleType.FIT_END);
i.setLayoutParams(new ListView.LayoutParams(60,60));
// Add ImageView to item view layout
oItemViewLayout.addView(i);
// TextView
TextView lblTextView = new TextView(mContext);
lblTextView.setText(mImageNames[position]);
// Add ImageView to item view layout
oItemViewLayout.addView(lblTextView);
return oItemViewLayout;
}
您还定义了一个字符串数组来保存图像的名称,可能像
private String[] mImageNames = {"title of video3", "video5", "music2",};
如果您为 ListItem 创建一个布局并加载它来创建视图,那就更容易了
创建一个名为“mylistview.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" >
<ImageView
android:id="@+id/ITEMVIEW_imgImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/ITEMVIEW_lblText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
然后你可以像这样创建getView() 方法
public View getView(int position, View convertView, ViewGroup parent)
{
// Create a new view or recycle one if available
View oItemViewLayout;
if (convertView == null)
{
// New view needs to be created
oItemViewLayout = (View)LayoutInflater.from(mContext).inflate(R.layout.mylistview, parent, false);
}
else
{
// Recycle an existing view
oItemViewLayout = (View)convertView;
}
// ImageView
ImageView i = (ImageView)oItemViewLayout.findViewById(R.id.ITEMVIEW_imgImage);
i.setImageResource(mImageIds[position]);
// TextView
TextView lblTextView = (TextView)oItemViewLayout.findViewById(R.id.IITEMVIEW_lblText);
lblTextView.setText(mImageNames[position]);
return oItemViewLayout;
}
这不仅通过允许您在 XML 中设计视图而让生活更轻松,而且它还将更加高效,因为您将回收已离开屏幕但仍在内存中的视图,因为您正在抓取 convertView 实例有的时候。