我想在Android中为网格视图中的图标添加标签。我找到了一些答案,但没有一个对我有效。大多数时候应用程序被强制关闭。 任何帮助将不胜感激。
这是我正在使用的代码
package com.appsdrip16;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(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;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(1, 1, 1, 1);
Bundle bundle=new Bundle();
bundle.putInt("key", position);
//Inflate the layout
LayoutInflater li = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View MyView = li.inflate(R.layout.main, null);
//View MyView;
// Add The Text!!!
TextView tv = (TextView) MyView.findViewById(R.id.grid_item_text);
tv.setText("Item "+ position );
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
// references to our images
private Integer[] mThumbIds = {
R.drawable.icon1, R.drawable.icon2,
R.drawable.icon3, R.drawable.icon4
};
}
答案 0 :(得分:0)
要实现此类自定义网格视图,您必须定义自定义行XML布局文件,然后在自定义适配器中对其进行充气,以用于带有图标和文本的GridView。