0

Я использую android.app.AlertDialog, который содержит ScrollView и внутри (конечно) некоторого контента.Android: Как добавить тонкую серая горизонтальную линию в диалоговом окне предупреждения перед кнопками?

Google показывает в своих материально-технических принципах небольшой серую линию выше кнопок, когда содержание больше видимое пространство: http://www.google.com/design/spec/components/dialogs.html#dialogs-behavior

Моя тревога-диалог не имеет эту серую линию. Как создать эту строку?

Я уже попробовал фон для ScrollView, как это:

<?xml version="1.0" encoding="utf-8"?> 
<shape 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle"> 
    <stroke 
     android:width="1dp" 
     android:color="@color/dark_transparent"/> 
</shape> 

Но это создало линию сверху и снизу. И это также появляется, когда содержимое меньше видимого пространства, которое выглядит уродливым.

ответ

2

Я нашел решение для серой линии! :)

Я нашел решение, как показать серую линию вообще здесь: How to make a static button under a ScrollView?

Для проверки, если я хочу, чтобы показать это, я нашел решение здесь: How can you tell when a layout has been drawn?

Это как мой код выглядит сейчас:

Это my_material_dialog.xml:

<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:orientation="vertical"> 

    <ScrollView 
     android:id="@+id/myMaterialDialog_scrollView" 
     android:layout_width="match_parent" 
     android:layout_height="0dp" 
     android:layout_weight="1" 
     android:fillViewport="true"> 

     <LinearLayout 
      android:id="@+id/myMaterialDialog_textView" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:orientation="vertical" 
      android:paddingBottom="5dp" 
      android:paddingLeft="26dp" 
      android:paddingRight="26dp" 
      android:paddingTop="15dp"> 
      <!-- dynamically added content goes here --> 
     </LinearLayout> 
    </ScrollView> 

    <View 
     android:id="@+id/myMaterialDialog_lineView" 
     android:layout_width="fill_parent" 
     android:layout_height="1dp" 
     android:layout_gravity="center_horizontal" 
     android:background="#15000000" 
     android:gravity="center_horizontal" 
     android:visibility="gone"/> 

</LinearLayout> 

И т его это MyMaterialDialog.java:

public class MyMaterialDialog extends AlertDialog { 

    private Context context; 
    private ScrollView scrollView; 
    private LinearLayout textView; 
    private View lineView; 
    private boolean checkingLayout; 

    public MyMaterialDialog(final Context context) { 
    super(context); 
    this.context = context; 

    final View myMaterialDialog = getLayoutInflater().inflate(R.layout.my_material_dialog, null); 
    this.scrollView = (ScrollView) myMaterialDialog.findViewById(R.id.myMaterialDialog_scrollView); 
    this.textView = (LinearLayout) myMaterialDialog.findViewById(R.id.myMaterialDialog_textView); 
    this.lineView = myMaterialDialog.findViewById(R.id.myMaterialDialog_lineView); 

    final ViewTreeObserver vto = scrollView.getViewTreeObserver(); 
    vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { 
     @Override 
     public void onGlobalLayout() { 
     if (checkingLayout) { 
      // avoid infinite recursions 
      return; 
     } 

     checkingLayout = true; 
     if (scrollView.canScrollVertically(1)) { 
      lineView.setVisibility(View.VISIBLE); 
     } else { 
      lineView.setVisibility(View.GONE); 
     } 
     checkingLayout = false; 
     } 
    }); 

    setTitle(R.string.myMaterialDialog_title); 
    setText(); 
    setView(myMaterialDialog); 

    show(); 
    } 

    /** 
    * do request to webserver for texts 
    */ 
    private final void setText() { 
    final GetDialogTextRequest request = new GetDialogTextRequest(); 
    final GetDialogTextResultHandler resultHandler = new GetDialogTextResultHandler(context, textView); 

    request.submit(resultHandler); 
    } 
} 

private final class GetDialogTextResultHandler extends DefaultRequestResultHandler<List<MyTextObject>> { 

    private final Context context; 
    private final LinearLayout textView; 

    private GetDialogTextResultHandler(final Context context, final LinearLayout textView) { 
    super(context); 
    this.context = context; 
    this.textView = textView; 
    } 

    @Override 
    public void handleResult(final List<MyTextObject> texts) { 
    setText(texts); // ... sets the content, can vary in size 
    } 
} 
0

Добавить что-то вроде этого под вашим ScrollView:

<View android:layout_width="fill_parent" 
android:layout_height="2px" 
android:background="#90909090"/> 

Это должно дать вам тонкий сероватый турник.

+0

гм, а не действительно работает. Когда я добавляю View, как вы сказали, мне нужно добавить еще один LinearLayout вокруг ScrollView и нового элемента, потому что разрешен только один корневой элемент. Тогда линия появляется ТОЛЬКО, когда нет прокрутки. Как только содержимое больше видимого пространства, линия исчезает. Но я хотел, чтобы это было наоборот: только линия, когда есть прокрутка. – nyx

+0

Возможно, вы могли бы использовать относительный макет, и тогда вы можете правильно расположить его. [См. Этот ответ] (http://stackoverflow.com/a/8271429/4428462). Чтобы показать это только при прокрутке, вы можете узнать, прокручивается ли ваш scrollView в вашем коде (попробуйте получить высоту содержимого и высоту scrollView и посмотреть, будет ли первое больше второго) и показать/скрыть представление горизонтальной полосы в зависимости от ситуации. – JonasCz

+0

Хм, это не так просто ...Когда я использую RelativeLayout, мне нужно установить высоту в wrap_content. Высота ScrollView также является wrap_content. Теперь, когда я установил ScrollView layout_alignParentTop = "true" и для Line-View android: layout_alignParentBottom = "true", он работает для линии. Но теперь у меня есть проблема, что высота диалога всегда на максимуме, даже если есть мало контента. Если я использую android: layout_below = "@ id/scrollView" для Line-View, размер диалогового окна прав, но теперь строка появляется только тогда, когда нет прокрутки. Такое же поведение, как у LinearLayout. – nyx

1

Если вы используете API 23+ (Android 6.0), используя следующие в целях прокрутки добавит верхние и нижние индикаторы.

android:scrollIndicators="top|bottom" 

Если таргетинг старых API, я заглянула в оповещения Диалог исходного контроллера кода Google, и я использую следующий код:

private static void setScrollIndicators(ViewGroup root, final NestedScrollView content, 
             final int indicators, final int mask) { 

//  use it like this: 
//  setScrollIndicators(contentPanel, content, indicators, 
//  ViewCompat.SCROLL_INDICATOR_TOP | ViewCompat.SCROLL_INDICATOR_BOTTOM); 

// Set up scroll indicators (if present). 
    View indicatorUp = root.findViewById(R.id.scrollIndicatorUp); 
    View indicatorDown = root.findViewById(R.id.scrollIndicatorDown); 

    if (Build.VERSION.SDK_INT >= 23) { 
     // We're on Marshmallow so can rely on the View APIsaa 
     ViewCompat.setScrollIndicators(content, indicators, mask); 
     // We can also remove the compat indicator views 
     if (indicatorUp != null) { 
      root.removeView(indicatorUp); 
     } 
     if (indicatorDown != null) { 
      root.removeView(indicatorDown); 
     } 
    } else { 
     // First, remove the indicator views if we're not set to use them 
     if (indicatorUp != null && (indicators & ViewCompat.SCROLL_INDICATOR_TOP) == 0) { 
      root.removeView(indicatorUp); 
      indicatorUp = null; 
     } 
     if (indicatorDown != null && (indicators & ViewCompat.SCROLL_INDICATOR_BOTTOM) == 0) { 
      root.removeView(indicatorDown); 
      indicatorDown = null; 
     } 

     if (indicatorUp != null || indicatorDown != null) { 
      final View top = indicatorUp; 
      final View bottom = indicatorDown; 

      if (content != null) { 
       // We're just showing the ScrollView, set up listener. 
       content.setOnScrollChangeListener(
         new NestedScrollView.OnScrollChangeListener() { 
          @Override 
          public void onScrollChange(NestedScrollView v, int scrollX, 
                 int scrollY, 
                 int oldScrollX, int oldScrollY) { 
           manageScrollIndicators(v, top, bottom); 
          } 
         }); 
       // Set up the indicators following layout. 
       content.post(new Runnable() { 
        @Override 
        public void run() { 
         manageScrollIndicators(content, top, bottom); 
        } 
       }); 
      } else { 
       // We don't have any content to scroll, remove the indicators. 
       if (top != null) { 
        root.removeView(top); 
       } 
       if (bottom != null) { 
        root.removeView(bottom); 
       } 
      } 
     } 
    } 
} 

private static void manageScrollIndicators(View v, View upIndicator, View downIndicator) { 
    if (upIndicator != null) { 
     upIndicator.setVisibility(
       ViewCompat.canScrollVertically(v, -1) ? View.VISIBLE : View.INVISIBLE); 
    } 
    if (downIndicator != null) { 
     downIndicator.setVisibility(
       ViewCompat.canScrollVertically(v, 1) ? View.VISIBLE : View.INVISIBLE); 
    } 
} 

И XML выглядит следующим образом:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:id="@+id/root" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:orientation="vertical"> 

<View 
    android:id="@+id/scrollIndicatorUp" 
    android:layout_width="match_parent" 
    android:layout_height="1dp" 
    android:background="@color/dim_white" 
    android:visibility="gone" 
    tools:visibility="visible" /> 

<android.support.v4.widget.NestedScrollView 
    android:id="@+id/scrollView" 
    android:layout_width="match_parent" 
    android:layout_height="0dp" 
    android:layout_weight="1"> 

    <... you content here> 

</android.support.v4.widget.NestedScrollView> 

<View 
    android:id="@+id/scrollIndicatorDown" 
    android:layout_width="match_parent" 
    android:layout_height="1dp" 
    android:background="@color/dim_white" 
    android:visibility="gone" 
    tools:visibility="visible" /> 
</LinearLayout> 
Смежные вопросы