RecyclerView实现GridView

时间:2016-09-04 04:48:33

标签: android gridview android-recyclerview

问题

我想使用RecyclerView来实施GridView。事实上,我需要在RecyclerView中显示包含3列的所有本地照片。我知道GridLayoutManager

我的代码:

   mManager = new GridLayoutManager(this,3);

项目XML

   <?xml version="1.0" encoding="utf-8"?>
  <ImageView xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content" />

但是如何设置项目视图(ImageView)的宽度和高度?

解决方案

我定义了一个自定义视图:

public class RatioImageView extends ImageView {

    private int originalWidth;
    private int originalHeight;


   public RatioImageView(Context context) {
       super(context);
   }


   public RatioImageView(Context context, AttributeSet attrs) {
      super(context, attrs);
   }   


    public RatioImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
   }


   public void setOriginalSize(int originalWidth, int originalHeight) {
       this.originalWidth = originalWidth;
       this.originalHeight = originalHeight;
   }


    @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
       if (originalWidth > 0 && originalHeight > 0) {
           float ratio = (float) originalWidth / (float) originalHeight;

           int width = MeasureSpec.getSize(widthMeasureSpec);
           int height = MeasureSpec.getSize(heightMeasureSpec);


           if (width > 0) {
               height = (int) ((float) width / ratio);
           }

           setMeasuredDimension(width, height);
       }
       else {
           super.onMeasure(widthMeasureSpec, heightMeasureSpec);
       }
   }
}

还有其他解决方案吗?

1 个答案:

答案 0 :(得分:1)

通过对您的回收商项目Custom ImageView进行充气,而不是在view onCreateViewHolder()方法内创建view,您可以将宽度和高度设置为{{1}使用layoutParamas。

如果你想要3列,那么你可以获得屏幕宽度并将其分成3并将其传递给ImageView并在RecyclerView Adapter中使用它来应用。