Как всегда выравнивать кнопку по нижней части экрана в фрагменте диалогового окна нижнего листа

У меня есть собственный класс, расширяющий BottomSheetDialogFragment, который будет отображаться при нажатии кнопки. Мой собственный макет BottomSheetDialogFragment состоит из 3 частей.

a.A Текст заголовка,

b. Группа радио (в которую я динамически добавляю n элементов)

c.Кнопка OK внизу (которую я хотел всегда отображать внизу)

Вот как это выглядит при нажатии кнопки. введите здесь описание изображения

На самом деле при первом запуске фрагмента моего диалога моя кнопка "ОК" не видна. Однако, когда я разворачиваю нижний лист, он выглядит так, как показано ниже, и моя кнопка "ОК" видна введите здесь описание изображения

Но мне нужно, чтобы всегда отображалась моя нижняя кнопка ОК, т.е. когда мой фрагмент диалога запускается, моя кнопка ОК должна присутствовать внизу, независимо от количества переключателей, которые у нее есть, и когда она развернута, тогда также Кнопка OK должна быть внизу, а мои переключатели должны иметь возможность прокрутки.

Ниже мой макет фрагмента диалога:

<?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"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>

<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/nested_scroll_view"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="25dp"
        android:layout_marginRight="20dp"
        android:layout_alignParentTop="true"
        android:text=""
        />


    <RadioGroup
        android:id="@+id/radiogroup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:layout_marginLeft="15dp"
        android:layout_below="@id/title"
        android:layout_marginBottom="10dp"
        >
    </RadioGroup>


    <android.widget.Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/ok"
        android:layout_below="@id/radiogroup"
        android:text="OK"
        android:layout_marginTop="10dp"
        android:layout_alignParentBottom="true"
        ></android.widget.Button>

</RelativeLayout>
</androidx.core.widget.NestedScrollView>
</LinearLayout>

Это мой пользовательский BottomSheetDialogFragment

public class BottomSheetExample extends BottomSheetDialogFragment {

@BindView(R.id.title)
TextView title;

@BindView(R.id.ok)
Button ok;

@BindView(R.id.nested_scroll_view)
NestedScrollView nestedScrollView;

@BindView(R.id.radiogroup)
RadioGroup radioGroup;

// TODO: Rename and change types of parameters

public BottomSheetExample() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.bottom_sheet, container, false);

    ButterKnife.bind(this, view);

    ArrayList<String> list = new ArrayList<>();
    for(int i=0;i<15;i++){
        list.add(""+i);
    }

    title.setText("Numbers");

    RadioGroup rg = radioGroup;

    for (int i = 0; i < list.size(); i++) {
        RadioButton rbn = new RadioButton(getContext());
        rbn.setId(View.generateViewId());
        String radioButtonText = list.get(i);
        rbn.setText(radioButtonText);
        rg.addView(rbn);
    }

    return view;
}   
}

Вот как я называю свой нижний лист:

BottomSheetExample bottomSheet = new BottomSheetExample();
bottomSheet.showNow(this.getSupportFragmentManager(), "tag");

Любые материалы будут очень полезны. Заранее спасибо!


comment
Я столкнулся с той же проблемой, вы нашли какое-либо решение?   -  person Himanshu    schedule 13.11.2019
comment
@Himanshu Я добавил свое решение.   -  person adi    schedule 22.11.2019
comment
@Himanshu, пожалуйста, поддержите мой ответ, если он вам полезен   -  person adi    schedule 24.11.2019


Ответы (3)


Наконец, я нашел исправление.

1. Чтобы правильно использовать нижний лист, я использую coordinatorlayout, а верхний LinearLayout имеет поведение нижнего листа.

2. Я поместил радиогруппу внутри вложенного прокрутки. Я хочу, чтобы максимальная высота вложенного прокрутки была фиксированной. Но, к сожалению, нет метода максимальной высоты. Таким образом, LinearLayout размещает вложенную прокрутку, внутри которой у нас есть радиогруппа. И теперь я установил высоту linearlayout, скажем, 300dp. Часть макета выполнена.

3. Теперь нам нужно исправить часть нижнего листа. Получите экземпляр BottomSheetBehaviour из верхнего LinearLayout, упомянутого в 1. Итак, теперь установите высоту просмотра нижнего листа, скажем, 300 dp. Это делается для исправления нижнего лист до определенной высоты, которая соответствовала бы варианту использования, упомянутому в вопросе.

XML:

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout                 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
>

<LinearLayout
    android:id="@+id/bottom_sheet_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior">

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

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:textStyle="bold"
            android:textSize="20sp"
            />

        <LinearLayout
            android:layout_below="@id/title"
            android:id="@+id/scroll_layout"
            android:layout_width="match_parent"
            android:layout_height="300dp">

            <androidx.core.widget.NestedScrollView
                android:id="@+id/nested_scroll_view"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fillViewport="true"
                app:layout_behavior="@string/appbar_scrolling_view_behavior">


                <RadioGroup
                    android:id="@+id/radiogroup"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/title"
                    android:layout_marginBottom="10dp" />

            </androidx.core.widget.NestedScrollView>

        </LinearLayout>

        <androidx.appcompat.widget.AppCompatButton
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="OK"
            android:id="@+id/click_btn"
            android:layout_below="@id/scroll_layout"/>

    </RelativeLayout>

</LinearLayout>

JAVA:

public class BottomSheetExample extends BottomSheetDialogFragment {

@BindView(R.id.title)
TextView title;

@BindView(R.id.click_btn)
Button ok;

@BindView(R.id.nested_scroll_view)
NestedScrollView nestedScrollView;

@BindView(R.id.radiogroup)
RadioGroup radioGroup;

@BindView(R.id.bottom_sheet_layout)
LinearLayout bottomSheetLayout;

private BottomSheetBehavior sheetBehavior;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.bottom_sheet, container, false);
    ButterKnife.bind(this, view);
    sheetBehavior = BottomSheetBehavior.from(bottomSheetLayout);
    sheetBehavior.setPeekHeight(R.dimen.peek_height);//put this ub dimens.xml (300dp)
    ArrayList<String> list = new ArrayList<>();
    for (int i = 0; i < 15; i++) {
        list.add("" + i);
    }
    title.setText("Numbers");
    RadioGroup rg = radioGroup;
    for (int i = 0; i < list.size(); i++) {
        RadioButton rbn = new RadioButton(getContext());
        rbn.setId(View.generateViewId());
        String radioButtonText = list.get(i);
        rbn.setText(radioButtonText);
        rg.addView(rbn);
    }
    return view;
}

}

Это решение действительно работает для меня! Любые предложения по улучшению всегда приветствуются!

person adi    schedule 22.11.2019
comment
Я сказал то же самое, но это не сработало. Не могли бы вы просмотреть эту тему?: stackoverflow.com/questions/66230902/ - person theoyuncu8; 20.02.2021

Можете ли вы попробовать это, поместив кнопку, обернутую в относительный макет вне вложенного представления прокрутки, может выполнить эту работу.

<?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"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <androidx.core.widget.NestedScrollView
        android:id="@+id/nested_scroll_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="25dp"
                android:layout_marginRight="20dp"
                android:text="" />


            <RadioGroup
                android:id="@+id/radiogroup"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/title"
                android:layout_marginLeft="15dp"
                android:layout_marginTop="15dp"
                android:layout_marginBottom="10dp"/>

        </RelativeLayout>

    </androidx.core.widget.NestedScrollView>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.widget.Button
            android:id="@+id/ok"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_gravity="bottom"
            android:layout_marginTop="10dp"
            android:gravity="bottom"
            android:text="OK" />

    </RelativeLayout>

</LinearLayout>
person vikas kumar    schedule 08.10.2019
comment
Спасибо за вклад, братан, но это не имитирует мое предполагаемое поведение .. оно показывает то же самое .. - person adi; 08.10.2019

Проверьте этот туриал: https://proandroiddev.com/android-bottom-sheet-behavior-and-animated-button-on-top-of-it-da86a9bfe545

Вам нужно создать прослушиватель для поведения нижнего листа и изменить положение кнопки на лету, принимая во внимание, скользит ли пользователь по дну или нет.

person mspapant    schedule 11.09.2020