Добавление вертикальной полосы прокрутки для AlertDialog в Android?

Я хотел бы добавить вертикальную полосу прокрутки к AlertDialog, потому что мой текст слишком длинный для отображения на 1 экране:

Я пытался использовать:

android:scrollbars="vertical" 
android:scrollbarAlwaysDrawVerticalTrack="true"

но полосы прокрутки даже не отображаются?

Вот файл макета xml, который я использую:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:scrollbars="vertical"
    android:scrollbarAlwaysDrawVerticalTrack="true"
    android:id="@+id/instructions_view" >
    <TextView
        android:id="@+id/TextView01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="A LONG TEXT 1"/>

    <TextView 
        android:id="@+id/TextView02"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="A LONG TEXT 2"/>

</LinearLayout>

Я вызываю AlertsDialog с:

public void onClick(View v) {
  switch(v.getId()){

    case R.id.Button_Instructions: 
     InstructionsDialog();
    break;

    case R.id.Button_Exit: 
     ExitDialog();
    break;
    }
 }

public void InstructionsDialog(){

  AlertDialog.Builder ad = new AlertDialog.Builder(this);
  ad.setIcon(R.drawable.icon);
  ad.setTitle("Instructions ...");
  ad.setView(LayoutInflater.from(this).inflate(R.layout.instructions_dialog,null));

  ad.setPositiveButton("OK", 
    new android.content.DialogInterface.OnClickListener() {
     public void onClick(DialogInterface dialog, int arg1) {
      // OK, go back to Main menu
     }
    }
   );

   ad.setOnCancelListener(new DialogInterface.OnCancelListener(){
    public void onCancel(DialogInterface dialog) {
     // OK, go back to Main menu   
    }}
   );

  ad.show();
 }

Я нашел ответ сейчас => С ЭТОМ РАБОТАЕТ СЕЙЧАС:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ScrollView01"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:scrollbars="vertical"
        android:scrollbarAlwaysDrawVerticalTrack="true"
        android:id="@+id/instructions_view" >

        <TextView
            android:id="@+id/TextView01"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="A LONG TEXT 1"/>

        <TextView
            android:id="@+id/TextView02"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="A LONG TEXT 2"/>

    </LinearLayout>
</ScrollView>

3 ответа

Чтобы прокручиваться представление, оно должно быть вложено в ScrollView контейнер:

<ScrollView>
    <LinearLayout android:orientation="vertical"
            android:scrollbars="vertical"
            android:scrollbarAlwaysDrawVerticalTrack="true">
        <TextView />
        <Button />
    </LinearLayout>
</ScrollView>

Обратите внимание, что ScrollView Контейнер может иметь только один дочерний вид компоновки. Например, невозможно разместить TextView а также Button в ScrollView без LinearLayout,

AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("YOUR_TITLE")
                .setMessage("YOUR_MSG")
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setIcon(android.R.drawable.ic_dialog_info)
                .show();
        TextView textView = (TextView) dialog.findViewById(android.R.id.message);
        textView.setMaxLines(5);
        textView.setScroller(new Scroller(this));
        textView.setVerticalScrollBarEnabled(true);
        textView.setMovementMethod(new ScrollingMovementMethod());

Весь найденный здесь код устарел.

Теперь вы должны использовать (в файле макета для вашего диалога)

NestedScrollView

<?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView 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:fillViewport="true"
    android:scrollbars="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

<androidx.constraintlayout.widget.ConstraintLayout 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:padding="16dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</androidx.constraintlayout.widget.ConstraintLayout>

</androidx.core.widget.NestedScrollView>

Кроме того, больше не рекомендуется использовать AlertDialogв одиночестве. Вы должны реализовать свой собственный DialogFragment, расширив DialogFragment.

См. https://developer.android.com/guide/topics/ui/dialogs.

Затем вы можете вызвать фрагмент вашего диалога:

MyDialogFragment dialogFragment = MyDialogFragment.newInstance();
dialogFragment.show(fragment.getFragmentManager(), MyDialogFragment.TAG);

В Android Q полосы прокрутки можно сделать всегда видимыми.

После создания и отображения диалогового окна найдите TextView с сообщением и измените его следующим образом. (Кстати, звонокsetMaxLines(5)просто ограничить количество видимых строк, чтобы продемонстрировать прокрутку. Установите как хотите, или удалите):

    TextView textView = (TextView) dialog.findViewById(android.R.id.message);
    textView.setMaxLines(5);
    textView.setVerticalScrollBarEnabled(true);
    textView.setMovementMethod(new ScrollingMovementMethod());
    textView.setScrollBarStyle(View.SCROLLBARS_INSIDE_INSET);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        textView.setScrollbarFadingEnabled(false);
        textView.setVerticalScrollbarTrackDrawable(m_mainActivity.getResources().getDrawable(R.drawable.scrollbar_track_vertical));
        textView.setVerticalScrollbarThumbDrawable(m_mainActivity.getResources().getDrawable(R.drawable.scrollbar_thumb_vertical));
    }

Требуются две чертежи.

Для app/src/main/res/drawable/scrollbar_thumb_vertical.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <gradient
        android:angle="0"
        android:endColor="#D8D8D8"
        android:startColor="#F7F7F7" />

    <corners android:radius="6dp" />

</shape>

И для app/src/main/res/drawable/scrollbar_thumb_vertical.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:angle="0"
        android:endColor="#757575"
        android:startColor="#A0A0A0" />

    <corners android:radius="6dp" />
</shape>

Используя это работает:

 .setScrollable(true)

Используйте это в вашем AlertDialogBox или MaterialStyledDialog.

 private void gettermsandconditions() {
    final MaterialStyledDialog dialogHeader_1 =
            new MaterialStyledDialog.Builder(this)
                    .setTitle("Terms and Conditions !")
                   // .setDescription("What can we improve? Your feedback is always welcome.")
                    .setDescription(R.string.Terms_and_condition)

                    .setIcon(R.drawable.bill_icon)
                    .setStyle(Style.HEADER_WITH_ICON)
                    .setHeaderColor(R.color.colorPrimary)
                    .withDarkerOverlay(true)
                    .setScrollable(true)
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                          //  startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + context.getPackageName())));
                        }
                    })
                    .setNegativeText("Ok")
                    .build();
    //.setStyle(Style.HEADER_WITH_TITLE)
    dialogHeader_1.show();

}
Другие вопросы по тегам