如何编程这样的布局?

时间:2017-03-08 22:02:10

标签: android xml button gridview layout

我想创建一个如下所示的布局: https://gyazo.com/2a08bcd731fb1cfeb07e72f75bc05e7e 我应该使用什么,它适合每个设备?

屏幕是我的,但问题是它不适合每个屏幕尺寸。 在某些设备上,它看起来像这样: https://gyazo.com/84d878061234c25ae872d4ed2491f2f4

以下是我用来表达这种布局的代码:

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

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <GridLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <Button
                android:id="@+id/button1"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:layout_columnWeight="1"
                android:layout_rowWeight="1"
                android:layout_column="0"
                android:layout_row="0"
                android:text="Button"/>

            <Button
                android:id="@+id/Button2"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:layout_columnWeight="1"
                android:layout_rowWeight="1"
                android:layout_column="1"
                android:layout_row="0"
                android:text="Button"/>

            <Button
                android:id="@+id/Button3"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:layout_columnWeight="1"
                android:layout_rowWeight="1"
                android:layout_column="0"
                android:layout_row="1"
                android:text="Button"/>

            <Button
                android:id="@+id/Button4"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:layout_rowWeight="1"
                android:layout_columnWeight="1"
                android:layout_column="1"
                android:layout_row="1"
                android:text="Button"/>

              //and 200 buttons more

    </GridLayout>

</ScrollView>

如何编制适合每种屏幕尺寸的布局? 重要的是ScrollView

1 个答案:

答案 0 :(得分:1)

首先想到的是将RecyclerView与GridLayoutManager一起使用

GridLayoutManager gridLayoutManager = new GridLayoutManager(context, 2, LinearLayoutManager.VERTICAL, false);
yourRecyclerView.setLayoutManager(gridLayoutManager);

这将为您提供一个垂直向下的列表,其中包含2列。如果你不介意的话,你可能也想查看CardView,但有时我喜欢一起使用它们。

为RecyclerView编写适配器后,您可以在活动中设置GridLayoutManager和YourAdapter,这几乎是您在活动中实际需要的唯一内容:初始化适配器,设置布局管理器和适配器您的Recyclerview,并完成。您需要自己编写适配器,但是有很多教程可以使用Google。

Here is a link我认为在我开始学习RecyclerView之前我已经遵循过了。有时以前所以我不确定它是否仍然正确,但你可以把它作为一个开始。

相关问题