我正在尝试使用this official example做某种GridView,我不知道如何在图片下方添加一些文字。我为适配器尝试了这个代码,但它无法正常工作:
public class ImageAdapterForGridView extends BaseAdapter {
private Context mContext;
public ImageAdapterForGridView(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
TextView textView = null;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(250, 250));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
textView = new TextView(mContext);
textView.setLayoutParams(new GridView.LayoutParams(100, 100));
textView.setPadding(8,8,8,8);
} else {
imageView = (ImageView) convertView;
//textView = (TextView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
textView.setText(mThumbTexts[position]);
return imageView;
}
/* public TextView getTextView(int position, TextView convertView, ViewGroup parent){
TextView textView;
if (convertView == null) { // if it's not recycled, initialize some attributes
textView = new TextView(mContext);
textView.setLayoutParams(new GridView.LayoutParams(100, 100));
textView.setPadding(8,8,8,8);
} else {
textView = convertView;
}
textView.setText(mThumbTexts[position]);
return textView;
}*/
// references to our images
private Integer[] mThumbIds = {
R.drawable.ic_facebook, R.drawable.ic_flickr,
R.drawable.ic_gmail, R.drawable.ic_linkedin,
R.drawable.ic_picasa, R.drawable.ic_myspace,
R.drawable.ic_rss, R.drawable.ic_skype,
R.drawable.ic_tuenti, R.drawable.ic_twitter,
R.drawable.ic_windowslive, R.drawable.ic_vimeo,
R.drawable.ic_yahoo, R.drawable.otro_32,
};
private String[] mThumbTexts = {
"Facebook", "Flickr", "Gmail", "LinkedIn", "Picasa", "Myspace", "RSS", "Skype", "Tuenti",
"Twitter", "WindowsLive", "Vimeo", "Yahoo", "Otros"
};
}
你知道我怎么能像添加imageView一样添加一些TextView?
非常感谢你的帮助:)。
答案 0 :(得分:1)
在getView
方法中,您将imageView
尝试将ImageView
和TextView
添加到LinearLayout
并返回该布局。
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
...
layout.addView(imageView);
layout.addView(textView);
...
return layout;
答案 1 :(得分:0)
如果您只想要带有标签的图像,您可以选择复合绘图。在Android中,textview可以具有与之关联的图像。您可以通过XML中的drawableTop/Left/Right/Bottom或以编程方式setCompoundDrawables来实现此目的。请查看我对此问题的回答,详细了解如何执行此操作:https://stackoverflow.com/a/26959558/1003528以及gridview的实用示例。