Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - how to change Recyclerview height dynamically?

Tags:

I'm stuck with an issue about changing Recycler height based on its total items. What I have tried is to use Layout Param like this:

        ViewGroup.LayoutParams params = myRecyclerView.getLayoutParams();
        params.height = itemHeight * numberOfItem;
        myRecyclerView.requestLayout();

or

       ViewGroup.LayoutParams params = new  RecyclerView.LayoutParams(..WRAP_CONTENT, ...WRAP_CONTENT);;
       params.height = itemHeight * numberOfItem;
       myRecyclerView..setLayoutParams(params);

But it didn't work. How can I do it ? Please help me !

like image 519
Lạng Hoàng Avatar asked Jul 14 '15 11:07

Lạng Hoàng


2 Answers

You should use LayoutParams of parent's view in setLayoutParams(params).

For example:

<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>

Change LayoutParams in the code.

  RelativeLayout.LayoutParams lp =
            new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, 500);
 recyclerView.setLayoutParams(lp);
like image 178
fuxi chu Avatar answered Sep 28 '22 11:09

fuxi chu


I tried this. It worked. May be help.

@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);
            }
        }
    });

}
like image 25
eurosecom Avatar answered Sep 28 '22 11:09

eurosecom