Android - 如何动态更改Recyclerview高度?

Lạn*_*àng 17 android android-recyclerview

我遇到了一个关于根据其总项目更改Recycler高度的问题.我试过的是使用这样的Layout Param:

        ViewGroup.LayoutParams params = myRecyclerView.getLayoutParams();
        params.height = itemHeight * numberOfItem;
        myRecyclerView.requestLayout();
Run Code Online (Sandbox Code Playgroud)

要么

       ViewGroup.LayoutParams params = new  RecyclerView.LayoutParams(..WRAP_CONTENT, ...WRAP_CONTENT);;
       params.height = itemHeight * numberOfItem;
       myRecyclerView..setLayoutParams(params);
Run Code Online (Sandbox Code Playgroud)

但它没有用.我该怎么做 ?请帮我 !

小智 11

您应该在setLayoutParams(params)中使用父视图的LayoutParams.

例如:

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >
    <android.support.v7.widget.RecyclerView
        android:id="@+id/images"
        android:layout_width="wrap_content"
        android:layout_height="360dp"
        >
    </android.support.v7.widget.RecyclerView>
 </Relativelayout>
Run Code Online (Sandbox Code Playgroud)

在代码中更改LayoutParams.

  RelativeLayout.LayoutParams lp =
            new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, 500);
 recyclerView.setLayoutParams(lp);
Run Code Online (Sandbox Code Playgroud)

  • 我刚刚将Linearlayout更改为Relative,然后它自动停留. (4认同)

eur*_*com 5

我试过了 有效。可能会有帮助。

@Override
public void onBindViewHolder(FeedListRowHolder feedListRowHolder, int i) {

    //this change height of rcv
     LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
     params.height =80; //height recycleviewer
     feedListRowHolder.itemView.setLayoutParams(params);

    FeedItem feedItem = feedItemList.get(i);

    Picasso.with(mContext).load(feedItem.getThumbnail())
            .error(R.drawable.placeholder)
            .placeholder(R.drawable.placeholder)
            .into(feedListRowHolder.thumbnail);

    feedListRowHolder.title.setText(Html.fromHtml(feedItem.getTitle()));
    feedListRowHolder.itemView.setActivated(selectedItems.get(i, false));

    feedListRowHolder.setClickListener(new FeedListRowHolder.ClickListener() {
        public void onClick(View v, int pos, boolean isLongClick) {
            if (isLongClick) {

                // View v at position pos is long-clicked.
                String poslx = pos + "";
                Toast.makeText(mContext, "longclick " + poslx, Toast.LENGTH_SHORT).show();

            } else {
                // View v at position pos is clicked.
                String possx = pos + "";
                Toast.makeText(mContext, "shortclick " + possx, Toast.LENGTH_SHORT).show();
                toggleSelection(pos);
            }
        }
    });

}
Run Code Online (Sandbox Code Playgroud)