Inflated ImageView to put in GalleryView isn't the right size

前端 未结 2 1273
挽巷
挽巷 2020-12-10 14:15

I am trying to inflate an ImageView that scales a Drawable that I can display in a GalleryView. My code to inflate the view seems to work fine, except that the attributes o

相关标签:
2条回答
  • 2020-12-10 14:34

    I'm not sure but this might work. Give an id to your imageview in your xml (say it is "@+id/image":

    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = getLayoutInflater();
        View view = (View) inflater.inflate(R.layout.gallery_item, null);
        ImageView i = (ImageView) view.findViewById(R.id.image);
        i.setImageResource(mImageIds.get(position));
        i.setScaleType(ImageView.ScaleType.FIT_XY);
    
        return view;
    }
    

    By the way you should optimize it checking if convertView is null in order to recycle views. Check this: http://code.google.com/events/io/2009/sessions/TurboChargeUiAndroidFast.html

    0 讨论(0)
  • 2020-12-10 14:49

    The trick is simply to use the following version of inflate():

    inflater.inflate(R.layout.gallery_item, parent, false);
    

    The last two parameters are mandatory. If you pass "null" as the parent, the inflater does not know what type of layout parameters to create and therefore ignores all the android:layout_ XML attributes. The last parameter simply tells the inflater to not add the inflated view to the parent right away. If you pass true (at least inside an Adapter's getView() method), bad things will happen.

    0 讨论(0)
提交回复
热议问题