我按以下方式尝试,但是在iv.setImageBitmap(bm)上出现了空指针异常。
我尝试使用网格视图和Layout Inflater设置带有文本的图像。我也进行了调试过程,但仍然无法解决问题。请检查以下代码。
public class CategoryAdapter extends BaseAdapter {
private Context mContext;
public static final int ACTIVITY_CREATE = 10;
int id=-1;
public CategoryAdapter(Context c) {
mContext = c;
}
public int getCount() {
return CategorylogoActivity.logoarray.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
Bitmap bm=null;
ImageView iv = null ;
TextView tv=null;
View v;
if(convertView==null){
@SuppressWarnings("static-access")
LayoutInflater li = (LayoutInflater)mContext.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
v = li.inflate(R.layout.category_icon, null);
tv= (TextView)v.findViewById(R.id.icon_text);
iv = (ImageView)v.findViewById(R.id.icon_image);
}
else
{
v = convertView;
}
try {
URL aURL = new URL(CategorylogoActivity.logoarray[position]);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
// Buffered is always good for a performance plus.
BufferedInputStream bis = new BufferedInputStream(is);
// Decode url-data to a bitmap.
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
iv.setImageBitmap(bm);
tv.setText(CategorylogoActivity.namearray[0]);
return v;
最佳答案
static class viewHolder {
ImageView iv = null ;
TextView tv=null;
}
public View getView(int position, View convertView, ViewGroup parent) {
Bitmap bm=null;
viewHolder vh;
View v;
if(convertView==null){
vh = new viewHolder();
@SuppressWarnings("static-access")
LayoutInflater li = (LayoutInflater)mContext.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
v = li.inflate(R.layout.category_icon, null);
vh.tv= (TextView)v.findViewById(R.id.icon_text);
vh.iv = (ImageView)v.findViewById(R.id.icon_image);
v.setTag(vh);
}
else
{
vh = (viewHolder)convertView.getTag();
v = convertView;
}
try {
URL aURL = new URL(CategorylogoActivity.logoarray[position]);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
// Buffered is always good for a performance plus.
BufferedInputStream bis = new BufferedInputStream(is);
// Decode url-data to a bitmap.
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
vh.iv.setImageBitmap(bm);
vh.tv.setText(CategorylogoActivity.namearray[0]);
return v;
您必须使用viewHolder类型的对象,当convertView不为null时,您的iv imageView为null。因此您在空对象上使用setImageBitmap()。试试我的代码。
HTH。
关于android - 如何在GridView中设置文字下方的图像?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7849962/