在此getView,编程视图生成中初始化RelativeLayout

时间:2014-10-01 20:37:06

标签: android getview convertview

我在一个适配器中使用getView,我正在创建一个imageview,并使其等于convertView之前已经初始化了视图。它包含图像缩略图,其中一些代表视频。

    @Override
    public View getView(int position, View convertView, ViewGroup container) {
        // First check if this is the top row

        if (position < mNumColumns) {
            if (convertView == null) {
                convertView = new View(mContext);
            }
            // Set empty view with height of ActionBar
            //convertView.setLayoutParams(new AbsListView.LayoutParams(
            //      LayoutParams.MATCH_PARENT, mActionBarHeight));
            return convertView;
        }

        // Now handle the main ImageView thumbnails
        ImageView imageView;
        if (convertView == null) { // if it's not recycled, instantiate and initialize
            imageView = new RecyclingImageView(mContext);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setLayoutParams(mImageViewLayoutParams);
        } else { // Otherwise re-use the converted view
            imageView = (ImageView) convertView;
        }

        // Check the height matches our calculated column width
        if (imageView.getLayoutParams().height != mItemHeight) {
            imageView.setLayoutParams(mImageViewLayoutParams);
        }

        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

        if(images.get(position - mNumColumns).getUriString().contains("video")){
            //display video icon
        }
        else
        {
            //don't display video icon
        }

        // Finally load the image asynchronously into the ImageView, this also takes care of
        // setting a placeholder image while the background thread runs
        if (images != null && !images.isEmpty())
            mImageFetcher.loadImage(images.get(position - mNumColumns).getUriString()/*.imageUrls[position - mNumColumns]*/, imageView);
        return imageView;
    }

缩略图上没有“播放”按钮来指定它们是视频,因此在这些情况下我需要以编程方式添加播放按钮。

通常我使用带有膨胀布局的视图模式,在这种情况下我没有这样做,因为我实际上不想在内存中存在某些东西。

所以我想以编程方式将RelativeLayout作为每个单元格的根视图(mRelativeLayout = (RelativeLayout)convertView),并将imageview和playbutton imageview添加到该转换视图中

我该怎么做?它需要修改此语句,但我不确定如何初始化所有重用的视图

   } else { // Otherwise re-use the converted view
            imageView = (ImageView) convertView;
        }

2 个答案:

答案 0 :(得分:3)

我认为这里最好的方法是使用一个返回不同类型视图的适配器(通过覆盖getViewTypeCount()getItemViewType()),例如{ {3}}

这样,您根本不需要以编程方式更改返回的视图。只需定义两个XML布局,并根据该位置的项目是否有视频来膨胀/重用其中一个或另一个。

这不仅会更加清晰,而且还会导致“转换”的性能损失。每当视频行作为convertView提供给另一个没有一个的项目时,一个视图到另一个视图,反之亦然

答案 1 :(得分:2)

我会让您的getView()始终返回RelativeLayout对象(我在下面称之为containerView),并将ImageView(s)作为子项添加到该对象中。

这里唯一的复杂因素是您需要为这些子标识符提供标识符,以便以后可以从回收的convertView中检索它们。请注意,我使用了内置的静态View.generateViewId(),这是API级别17.如果您需要它在API级别17之前工作,您可以使用唯一的整数创建自己的ID(例如1 ,2等) - 只要确保它们不大于0x0FFFFFF更新:我添加了以下用于此目的的代码。

请参阅我在下面的几点中添加的评论。

@Override
public View getView(int position, View convertView, ViewGroup container) {
    // First check if this is the top row
    if (position < mNumColumns) {
        if (convertView == null) {
            convertView = new View(mContext);
        }
        // Set empty view with height of ActionBar
        //convertView.setLayoutParams(new AbsListView.LayoutParams(
        //      LayoutParams.MATCH_PARENT, mActionBarHeight));
        return convertView;
    }

    // Now handle the main ImageView thumbnails
    RelativeLayout containerView;
    ImageView imageView;
    ImageView videoIconView;   // TODO:  or whatever type you want to use for this...
    if (convertView == null) { // if it's not recycled, instantiate and initialize
        containerView = new RelativeLayout(mContext);
        // TODO:  The layout params that you used for the image view you probably 
        // now want to use for the container view instead...
        imageView.setLayoutParams(mImageViewLayoutParams);   // If so, you can change their name...

        imageView = new RecyclingImageView(mContext);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        //imageView.setLayoutParams(mImageViewLayoutParams);   // This probably isn't needed any more.

        // Generate an Id to use for later retrieval of the imageView...
        // This assumes it was initialized to -1 in the constructor to mark it being unset.
        // Note, this could be done elsewhere in this adapter class (such as in
        // the constructor when mImageId is initialized, since it only
        // needs to be done once (not once per view) -- I'm just doing it here
        // to avoid having to show any other functions.
        if (mImageId == -1) {
            mImageId = View.generateViewId();
        }
        imageView.setId(mImageId);

        containerView.addView(imageView, RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);

        // NOTE:  At this point, I would personally always just add the video icon
        // as a child of containerView here no matter what (generating another unique 
        // view Id for it, mVideoIconId, similar to how was shown above for the imageView) 
        // and then set it to either VISIBLE or INVISIBLE/GONE below depending on whether
        // the URL contains the word "video" or not.  
        // For example:
        vidoIconView = new <whatever>;
        // TODO:  setup videoIconView with the proper drawable, scaling, etc. here...
        if (mVideoIconId == -1) {
            mVideoIconId = View.generateViewId();
        }
        videoIconView.setId(mVideoIconId);
        containerView.addView(videoIconView, RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        final RelativeLayout.LayoutParams layout = ((RelativeLayout.LayoutParams)containerView.getLayoutParams());
        layout.addRule(RelativeLayout.LayoutParams.CENTER_HORIZONTAL);   // ... or whatever else you want
        layout.addRule(RelativeLayout.LayoutParams.ALIGN_PARENT_BOTTOM);  // ... or whatever else you want
    } else {
        // Otherwise re-use the converted view
        containerView = (RelativeLayout) convertView;
        imageView = containerView.findViewById(mImageId);
        videoIconView = containerView.findViewById(mVideoIconId);  // see comment above
    }


    // Check the height matches our calculated column width
    if (containerView.getLayoutParams().height != mItemHeight) {
        containerView.setLayoutParams(mImageViewLayoutParams);
    }

    if(images.get(position - mNumColumns).getUriString().contains("video")){
        //display video icon
        // see comment above, here you can probably just do something like:
        videoIconView.setVisibility(View.VISIBLE);
    }
    else
    {
        //don't display video icon
        videoIconView.setVisibility(View.GONE);  // could also use INVISIBLE here... up to you.
    }

    // Finally load the image asynchronously into the ImageView, this also takes care of
    // setting a placeholder image while the background thread runs
    if (images != null && !images.isEmpty())
        mImageFetcher.loadImage(images.get(position - mNumColumns).getUriString()/*.imageUrls[position - mNumColumns]*/, imageView);
    return containerView;
}

<强>更新
在回答评论中的问题时,我使用类似的东西(在我的自定义“ViewController”基类中):

private static int s_nextGeneratedId = 1;

/** 
 * Try to do the same thing as View.generateViewId() when using API level < 17.
 * @return Unique integer that can be used with setId() on a View.
 */
protected static int generateViewId() {
    // AAPT-generated IDs have the high byte nonzero; clamp to the range under that.
    if (++s_nextGeneratedId > 0x00FFFFFF)
        s_nextGeneratedId = 1;  // Roll over to 1, not 0.
    return s_nextGeneratedId;
}

请注意,网格中的每个单元格都不需要唯一的视图ID。相反,您只需要为可能想要使用findViewById()访问的每种类型的子视图使用它。因此,在您的情况下,您可能只需要两个唯一ID。由于从您的xml布局文件自动生成的视图ID到R.java通常非常大,我发现只需对我的手工生成的ID使用较小的数字(如上所示)。