Android:具有水平方向的LinearLayout将元素推离屏幕

时间:2017-08-16 10:58:24

标签: android android-layout android-fragments

我有一个LinearLayout:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">
    <LinearLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

    </LinearLayout>
</ScrollView>

我用动态添加的片段填充

void add_item(){
        Database database = new Database(this);
        String[] categories = database.getCategories();
        LinearLayout layout = (LinearLayout)findViewById(R.id.container);
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        if (categories.length>0) {
            for (String category : categories){
                FrameLayout frame = new FrameLayout(this);
                int id = View.generateViewId();
                frame.setId(id);
                layout.addView(frame);
                Fragment itemsFragment = CategoryFragment.newInstance(R.drawable.body, category);
                ft.add(id, itemsFragment);
            }
            Log.i("test","success");
        }
        ft.commit();
    }

问题是碎片会离开屏幕。我实际上想要片段水平,只有当我的空间用完时才会向下移动。有可能吗?

2 个答案:

答案 0 :(得分:2)

不幸的是,LinearLayout无法做到这一点。您必须将每个视图的所有宽度相加,然后当它们超出屏幕宽度时,在下面创建一个新的LinearLayout并开始填充它。不太优雅。

为了解决这个问题,Google创建了Flexbox库来模仿CSS中可用的行为。 Take a look at it here

答案 1 :(得分:0)

首先 - 你的线性布局方向是&#34;水平&#34;,所以它会尝试将所有孩子连续推入,而不是列。

此外,您应该尝试使用RecyclerView,而不是使用LinearLayout,因为开销会将所有视图存储在内存中并保持绘图。 Here is how to do it by Google