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

Android:LinearLayout具有水平方向,可将元素推离屏幕,android,android-layout,android-fragments,Android,Android Layout,Android Fragments,我有一个线性布局: 问题是碎片会从屏幕上消失。实际上,我希望碎片水平移动,只有在空间用完时才能在下方移动。有可能吗?很遗憾,线性布局无法做到这一点。您必须将每个视图的所有宽度相加,然后当它们超过屏幕宽度时,在下面创建一个新的线性布局并开始填充。不太优雅 为了解决这个问题,Google创建了Flexbox库来模拟CSS中所需的行为 首先-线性布局的方向是“水平的”,因此它将尝试将所有子级推到一行中,而不是一列中 此外,您应该真正尝试使用RecyclerView,而不是LinearLayout,因为

我有一个线性布局:


问题是碎片会从屏幕上消失。实际上,我希望碎片水平移动,只有在空间用完时才能在下方移动。有可能吗?

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


为了解决这个问题,Google创建了Flexbox库来模拟CSS中所需的行为

首先-线性布局的方向是“水平的”,因此它将尝试将所有子级推到一行中,而不是一列中


此外,您应该真正尝试使用RecyclerView,而不是LinearLayout,因为将所有视图存储在内存中并使其保持绘图的开销

您是否应该将线性布局的方向更改为垂直?@AjilO。如果我这样做了,他们会排成一行。仅仅阅读一次问题就有点不清楚了。为了得到更好的回答,您可能应该在问题中添加一个事实,即您实际上希望碎片水平移动,并且只有在空间不足时才移动到下方。:)@阿吉洛。编辑。尝试使用网格布局。我想我会制作一个片段,使其适合屏幕宽度,并将方向更改为垂直。稍后我会尝试你的方法。Flexbox看起来非常有用。非常感谢。
<?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();
    }