在findbyView之后,ImageView仍为null

时间:2012-06-01 12:45:34

标签: android android-layout android-listview nullpointerexception

嘿我试图让List工作,在这种情况下我有一个xml定义的项目,我在扩展的ArrayAdapter中膨胀。但是在我膨胀了xml后,当我尝试抓取imageview时,它会通过findviewbyid返回null ... 这是项目的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" >
    <TextView 
        android:id="@+id/product_item_textview"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="if no image avail show this"
        android:visibility="gone"/>
    <ImageView 
        android:id="@+id/product_item_imageview"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:visibility="visible"
        />

</LinearLayout>

实例化项目的方法:

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        SimpleListItem item= items.get(position);
        LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = vi.inflate(R.layout.product_item, null);
        if(item.getPicture()!=null)
        {
            ImageView imgVw = (ImageView) findViewById(R.id.product_item_imageview);
            String picturePath = item.getPicture();
            Bitmap picture = ImageManager.get(getBaseContext(), picturePath);
            imgVw.setImageBitmap(picture);
        } else {
            TextView txtVw = (TextView) findViewById(R.id.product_item_textview);
            txtVw.setText(item.getText());
            txtVw.setVisibility(View.VISIBLE);
        }
        return v;
    }

2 个答案:

答案 0 :(得分:3)

它的一个,

  ImageView imgVw = (ImageView) v.findViewById(R.id.product_item_imageview);

TextView

也是如此
 TextView txtVw = (TextView) v.findViewById(R.id.product_item_textview);

使用View v从充气的xml文件中获取ImageViewTextView

答案 1 :(得分:1)

//您正在视图v中展开布局,因此您需要通过

获取它们
ImageView imgVw = (ImageView)v. findViewById(R.id.product_item_imageview);


TextView txtVw = (TextView)v. findViewById(R.id.product_item_textview);