首页 > 解决方案 > 如何在 LinearLayout 中的另一个视图下移动视图?

问题描述

我似乎无法为我的问题找到正确的关键字。不要与 XML 布局编辑混淆,我可以在容器内以编程方式将一个实时移动到另一个View下吗?ViewLinearLayout

这是我的主要布局 XML 文件。只需将两个按钮拖到 UI 编辑器并命名它们即可:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:background="#000000"
    android:id="@+id/main_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button 1" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button 2" />
</LinearLayout>

假设我在我的应用程序中做了一些事情,然后突然button1向下移动button2并向上移动button2。我怎样才能做到这一点?是否my1Button.shiftDown();存在类似或类似的东西?

标签: androidandroid-linearlayout

解决方案


您需要使用线性布局的子级。像这样的东西:

public void reorderButtons() {
    LinearLayout layout = (LinearLayout) findViewById(R.id.main_layout);

    View button1 = layout.getChildAt(0);
    View button2 = layout.getChildAt(1);

    // Remove both buttons
    layout.removeAllViews();

    // Add the buttons in the order you want
    layout.addView(button2);
    layout.addView(button1);
}

推荐阅读