Android: 动态按钮布局 + FAB + Appbar

Android: Layout for dynamic buttons + FAB + Appbar

我是 Android(和 Java)的新手,对布局有困难。

当我点击 FAB 时,应该会创建一个按钮。据我所知,当我想以编程方式添加按钮时,我必须使用 LinearLayout。这通常是可行的,但是当我尝试将 LinearLayout 与 FAB 和 appbar 结合使用时,新创建的按钮未显示或者 FAB 或 appbar。

其中一个布局总是隐藏一些其他元素。它应该是这样的:

  1. 应用栏

  2. LinearLayout - 带滚动条的按钮

  3. 右下角FAB

我尝试了 RelativeLayout、FrameLayout、CoordinatorLayout 等,但没有成功。

activity_main.xml

<android.support.design.widget.CoordinatorLayout 
    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"
    tools:context="xyz.mypackage.MainActivity">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/main_layout">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

</LinearLayout>

<!--include layout="@layout/content_main" /-->

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/fab_margin"
    android:visibility="visible"
    app:srcCompat="@android:drawable/ic_input_add" />

</android.support.design.widget.CoordinatorLayout>

在 xml 中创建按钮并将可见性设置为消失。 Fab 单击触发 dialogfragment,要获取输入,您可以包含 EditText。

EditText editText = (EditText) getDialog().findViewById(R.id.project_name);
if (editText != null) {
    Log.e("Value", editText.getText().toString());
    button.setText(editText.getText().toString());
    button.setVisibility(View.VISIBLE);
} else {
    Log.e("", "EditText not found!");
}

如何从 DialogFragment 中的 EditText 获取文本?

getText from a EditText in a DialogFragment

阅读文档后(是的,我应该在发布问题之前这样做),我找到了一种方法:

作为 root,使用 RelativeLayout,然后为应用栏和按钮使用 LinearLayout 作为子项(我还添加了一个带有另一个 LinearLayout 的 ScrollView)。 FAB 应该位于具有以下属性的根 (RelativeLayout) 中:

android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"