[英]How to set image with text having below it in gridview?
我按以下方式嘗試,但是在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;
您不應該在適配器中執行URLConnection,這將嘗試進行多重連接,因為每次在適配器中顯示該視圖時都會調用getView()。 而是在單獨的類中處理連接。
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。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.