RecyclerView GridLayoutManager: how to auto-detect span count?

后端 未结 13 594
没有蜡笔的小新
没有蜡笔的小新 2020-11-28 18:45

Using the new GridLayoutManager: https://developer.android.com/reference/android/support/v7/widget/GridLayoutManager.html

It takes an explicit span count, so the pro

13条回答
  •  感情败类
    2020-11-28 18:48

    1. Set minimal fixed width of imageView (144dp x 144dp for example)
    2. When you create GridLayoutManager, you need to know how much columns will be with minimal size of imageView:

      WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE); //Получаем размер экрана
      Display display = wm.getDefaultDisplay();
      
      Point point = new Point();
      display.getSize(point);
      int screenWidth = point.x; //Ширина экрана
      
      int photoWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 144, this.getResources().getDisplayMetrics()); //Переводим в точки
      
      int columnsCount = screenWidth/photoWidth; //Число столбцов
      
      GridLayoutManager gridLayoutManager = new GridLayoutManager(this, columnsCount);
      recyclerView.setLayoutManager(gridLayoutManager);
      
    3. After that you need to resize imageView in adapter if you have space in column. You may send newImageViewSize then inisilize adapter from activity there you calculate screen and column count:

      @Override //Заполнение нашей плитки
      public void onBindViewHolder(PhotoHolder holder, int position) {
         ...
         ViewGroup.LayoutParams photoParams = holder.photo.getLayoutParams(); //Параметры нашей фотографии
      
         int newImageViewSize = screenWidth/columnsCount; //Новый размер фотографии
      
         photoParams.width = newImageViewSize; //Установка нового размера
         photoParams.height = newImageViewSize;
         holder.photo.setLayoutParams(photoParams); //Установка параметров
         ...
      }
      

    It works in both orientations. In vertical I have 2 columns and in horizontal - 4 columns. The result: https://i.stack.imgur.com/WHvyD.jpg

提交回复
热议问题