我正在尝试从数组中加载图像列表。我在列表中得到了图像。现在我需要为列表中的每个图像添加一个文本。有人可以帮我弄这个吗?我是Android的新手。
public class EfficientAdapter extends BaseAdapter {
public EfficientAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mImageIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
i.setImageResource(mImageIds[position]);
i.setScaleType(ImageView.ScaleType.FIT_END);
i.setLayoutParams(new ListView.LayoutParams(60, 60));
return i;
}
private Context mContext;
private Integer[] mImageIds = { R.drawable.video3, R.drawable.video5, R.drawable.music2, };
}
这是我的代码,我从数组中加载了图像列表。请帮我这个代码。
答案 0 :(得分:1)
您可以执行类似
的操作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设计视图,这不仅会让生活变得更轻松,而且还会更有效率,因为您将重新回收已经离开屏幕但仍然在内存中的视图,因为您抓住了{{1}当有一个实例时。