簡體   English   中英

如何在 RecyclerView 中顯示確切的項目數量?

[英]How to show exact number of items in RecyclerView?

我試圖在 RecyclerView 中顯示精確(例如 3 個項目)。 我們的 Web 應用程序顯示如下:

在此處輸入圖片說明

如果我移動項目:

在此處輸入圖片說明

然后松開鼠標,它會自動出現: 在此處輸入圖片說明

在 Android 中,我使用 RecyclerView 顯示圖像:

在此處輸入圖片說明

如何在 RecyclerView 的可見區域中准確顯示 3 個項目? 如何避免顯示“一半”項目? 這可能嗎?

回收者視圖:

        <android.support.v7.widget.RecyclerView
            android:layout_width="wrap_content"
            android:layout_height="130dp"
            android:id="@+id/rvProducts" />

回收商視圖中的一項:

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

    <ImageView
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:id="@+id/ivProduct"
        android:src="@drawable/noimage"/>

</LinearLayout>

代碼:

    LinearLayoutManager layoutManager
            = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
    RecyclerView productImageList = (RecyclerView) view.findViewById(R.id.rvProducts);
    productImageList.setLayoutManager(layoutManager);
    GalleryRecyclerAdapter adapter = new GalleryRecyclerAdapter(images);
    productImageList.setAdapter(adapter);

一種解決方案是以編程方式設置每個孩子的width

view.getLayoutParams().width = getScreenWidth() / VIEWS_COUNT_TO_DISPLAY;

屏幕尺寸是這樣的:

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics).widthPixels;

我已經按照以下方法完成了上述任務,請參考以下代碼

在我的RecycleView Adapter onCreateViewHolder()方法中,我找出了屏幕的寬度,然后將其分為3 個部分。請檢查一次。

@Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.MY_ITEM_TO_INFALTE, parent, false);

        itemView.getLayoutParams().width = (int) (getScreenWidth() / NUMBERS_OF_ITEM_TO_DISPLAY); /// THIS LINE WILL DIVIDE OUR VIEW INTO NUMBERS OF PARTS

        return new MyCreationItemAdapter.MyViewHolder(itemView);
    }

從上面的代碼中,我們在上面使用的getScreenWidth()方法如下,請檢查它。

public int getScreenWidth() {

        WindowManager wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);

        return size.x;
    }

在實現這一點的一般方法中,回收者視圖沒有直接的屬性。

實現這一點的方法是將父寬度發送到適配器。

以一種麂皮的方式..

    Parent width = parent container width;

    InitialiseRecyclerAdapter(parent width) {
         on create view holder {
                 Set the width of ur item layout with a width that divides ur parent width in equal parts;
          }
}

這個解決方案對我有用:

 private lateinit var productImageList: RecyclerView

 override fun onAttachedToRecyclerView(recyclerView: RecyclerView) 
  {
       super.onAttachedToRecyclerView(recyclerView)

        productImageList = recyclerView
  }

 override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProductViewHolder {
        val viewHolder = LayoutInflater.from(parent.context).inflate(R.layout.ITEM_TO_INFALTE, parent, false)

        viewHolder.layoutParams.width = productImageList.measuredWidth / NUMBERS_OF_ITEM_TO_DISPLAY

        return ProductViewHolder(viewHolder)
    }

代碼在 kotlin 中,希望對您有所幫助。

我在下面提供的解決方案有助於在屏幕上的 recyclerView 中顯示預定義數量的子項目(' numOfCardViewItemsOnScreen '),還計算這些項目之間的邊距以均勻間隔它們,通過考慮之間提供的邊距items & recyclerView 的結束邊距(即,' marginAtRecyclerViewsEnds ')

請注意,我已經在 5.0" 到 7.0" 英寸設備之間進行了測試,並獲得了一致的結果。

private fun configureCardViewLayoutParams(cardView: CardView, numOfCardViewItemsOnScreen: Int, marginAtRecyclerViewsEnds: Float, marginLeftParam: Float, marginRightParam: Float, marginTopParam: Float, marginBottomParam: Float): ViewGroup.MarginLayoutParams {
    val numOfGapsInBetweenItems = numOfCardViewItemsOnScreen - 1
    var combinedGapWidth = ((marginLeftParam + marginRightParam) * numOfGapsInBetweenItems) + (marginAtRecyclerViewsEnds * 2)
    //Provided approx. adjustment of 2dp to prevent the extreme edges of the card from being cut-off
    combinedGapWidth += 2
    val combinedGapWidthDp = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, combinedGapWidth, cardView.resources.displayMetrics).toInt()
    //Since margins/gaps are provided in-between the items, these have to be taken to account & subtracted from the width in-order to obtain even spacing
    cardView.layoutParams.width = (getScreenWidth(cardView.context as MainActivity) - combinedGapWidthDp) / numOfCardViewItemsOnScreen

    //Margins in-between the items
    val marginLeftOfItem = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, marginLeftParam, cardView.resources.displayMetrics).toInt()
    val marginRightOfItem = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, marginRightParam, cardView.resources.displayMetrics).toInt()
    val marginTopOfItem = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, marginTopParam, cardView.resources.displayMetrics).toInt()
    val marginBottomOfItem = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, marginBottomParam, cardView.resources.displayMetrics).toInt()

    //Providing the above margins to the CardView
    val cardViewMarginParams: ViewGroup.MarginLayoutParams = cardView.layoutParams as ViewGroup.MarginLayoutParams
    cardViewMarginParams.setMargins(marginLeftOfItem, marginTopOfItem, marginRightOfItem, marginBottomOfItem)
    return cardViewMarginParams
}

顧名思義,以下方法有助於計算 screenWidth

private fun getScreenWidth(activity: MainActivity): Int {
    var width: Int = 0
    val size = Point()
    val windowManager = activity.getSystemService(Context.WINDOW_SERVICE) as WindowManager
    width = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        val bounds = windowManager.currentWindowMetrics.bounds
        bounds.width()
    } else {
        val display: Display? = windowManager.defaultDisplay
        display?.getSize(size)
        size.x
    }
    return width
}

最后在 onCreateViewHolder 中,利用上面描述的 configureCardViewLayoutParams 方法並傳入所需的參數

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyRecyclerViewHolder {
    val view = LayoutInflater.from(parent.context).inflate(R.layout.row_item_layout, parent, false)
    view.layoutParams = configureCardViewLayoutParams(view as CardView, 4, 12f, 4f, 4f, 8f, 8f)
    return MyRecyclerViewHolder(view)
}

為了便於理解,我還提供了子項的xml布局(row_item_layout.xml),所以從下面的xml可以看出,我們子項布局的根視圖是一個CardView。

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:elevation="5dp"
    android:foregroundGravity="center">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="30dp"
            android:layout_height="28dp"
            android:layout_marginTop="22dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            tools:src="@tools:sample/avatars" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="7dp"
            android:layout_marginTop="18dp"
            android:layout_marginEnd="7dp"
            android:layout_marginBottom="16dp"
            android:ellipsize="end"
            android:gravity="center"
            android:maxLines="2"
            android:text="@{accountOptionsModel.title}"
            android:textSize="14sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/imageView1"
            tools:text="@tools:sample/full_names" />
    </androidx.constraintlayout.widget.ConstraintLayout>


</androidx.cardview.widget.CardView>

getCount() 中沒有特殊邏輯,只返回整個列表大小

override fun getItemCount(): Int = myList.size

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM