如何在RecyclerView或ListView项目视图中使用layout_weight使相等高度的项目填满屏幕上的可用空间? [英] How can I use layout_weight in RecyclerView or ListView item view to have items of equal height fill up the available space on screen?

查看:403
本文介绍了如何在RecyclerView或ListView项目视图中使用layout_weight使相等高度的项目填满屏幕上的可用空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前需要使用RecyclerView(或ListView),但项目数固定为4.我希望这4个项目平均使用屏幕上的可用空间.除了应用程序栏外,RecyclerView是屏幕上唯一的视图. IE. RecyclerView已将layout_height设置为match_parent.之所以选择RecyclerView,是因为根据模型的状态,物品的布局不同.

I currently have a need to use a RecyclerView (or ListView) but the number of items is fixed at 4. I want those 4 items to equally use the available space on the screen. The RecyclerView is the only view on the screen except for the app bar. I.e. RecyclerView has layout_height set to match_parent. I chose the RecyclerView because the items have different layouts depending on model state.

我还没有查找它,但是我敢肯定我可以用Java代码以编程方式为每个项目设置高度.但是,如果我可以在XML中指定它,那似乎并不理想.在我撰写本文时,右边的类似问题也回答了该问题.

I haven't looked it up yet, but I'm sure I can set the height programmatically in Java code for each item. But that seems inelegant if I can specify it in the XML. Similar questions to my right, as I write this, answer that question.

我已经在item_layout.xml文件中尝试了以下方法,在其他情况下使用layout_weight的方式:

I've tried the following in the item_layout.xml file, the way layout_weight is used in other scenarios:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_weight="1"
    android:layout_height="0dp">...</LinearLayout>

但是随后屏幕上没有任何显示.

But then nothing shows on screen.

我想知道的是,我可以使用layout_weight在布局XML中执行此操作,还是执行其他操作?如果是这样,怎么办?

What I'd like to know is, can I do this in the layout XML with layout_weight, or something else? If so, how?

推荐答案

作为 API参考表示,layout_weightLinearLayout的属性,因此它不能与其他ViewGroup(例如,RecyclerViewListView)一起使用.相反,您必须以编程方式设置项目的高度.

As the API reference says, layout_weight is an attribute of LinearLayout, so it cannot be used with other ViewGroups like, for instance, RecyclerView and ListView. Instead, you have to set the item's height programmatically.

由于您似乎担心代码的整洁性,因此,如果您使用RecyclerView,我认为这是一个非常优雅的解决方案:

Since you seem worried about your code's cleanliness, I think this is a rather elegant solution in case you use a RecyclerView:

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater
            .from(parent.getContext())
            .inflate(R.layout.item_list, null);

    int height = parent.getMeasuredHeight() / 4;
    int width = parent.getMeasuredWidth();

    view.setLayoutParams(new RecyclerView.LayoutParams(width, height));

    return new ViewHolder(view);
}

这篇关于如何在RecyclerView或ListView项目视图中使用layout_weight使相等高度的项目填满屏幕上的可用空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆