2015-08-11 6 views
2

фона:

Я работаю на доказательство концепции для моей работы. Требование: при первом запуске приложения открывается приветственный экран, чтобы ввести пользователя в приложение и новые функции. Там все прекрасное и денди. Экран приветствия - это длинный прокручиваемый список разделов, посвященный новым функциям. Когда этот прокручиваемый список открывается первым, в середине экрана должно быть 2 текстовых раздела, а текст в нижней части экрана позволяет пользователю узнать прокрутку вниз для большего. После этого каждый раздел должен в основном просто обернуть его содержимое. Я нашел способ заставить его работать, но мне сложно понять, КАК И ПОЧЕМУ это работает. Вот код, который работает.Android OnGlobalLayoutListener, что происходит здесь

Планировка:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" 
     xmlns:tools="http://schemas.android.com/tools" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:fillViewport="true" 
     tools:context=".MainActivity" > 

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

    <!-- first section --> 
    <LinearLayout 
     android:id="@+id/f1" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:orientation="vertical"> 

     <TextView 
      android:id="@+id/tv1" 
      android:layout_width="wrap_content" 
      android:layout_height="0dp" 
      android:layout_weight="1" 
      android:text="top text" 
      android:layout_gravity="center_horizontal" 
      android:gravity="bottom" 
      android:paddingTop="35dp" 
      android:textColor="@android:color/holo_red_dark"/> 

     <TextView 
      android:layout_width="wrap_content" 
      android:layout_height="0dp" 
      android:layout_weight="1" 
      android:text="middle text" 
      android:layout_gravity="center_horizontal" 
      android:textColor="@android:color/holo_red_dark"/> 

     <TextView 
      android:layout_width="wrap_content" 
      android:layout_height="0dp" 
      android:layout_weight="1" 
      android:text="bottom text" 
      android:layout_gravity="center_horizontal" 
      android:gravity="bottom" 
      android:textColor="@android:color/holo_red_dark"/> 
    </LinearLayout> 

    <!-- second section --> 
    <ImageView 
     android:id="@+id/f2" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:background="#ff8222"/> 

    <!-- third section --> 
    <ImageView 
     android:id="@+id/f3" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:background="@android:color/darker_gray"/> 
</LinearLayout> 

Java:

final LinearLayout layout = (LinearLayout)findViewById(R.id.linlayout); 
final LinearLayout f1=(LinearLayout) findViewById(R.id.f1); 
final ImageView f2=(ImageView) findViewById(R.id.f2); 
final ImageView f3=(ImageView) findViewById(R.id.f3); 
ViewTreeObserver vto = layout.getViewTreeObserver(); 
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { 
    @Override 
    public void onGlobalLayout() { 
     layout.getViewTreeObserver().removeOnGlobalLayoutListener(this); 
     int width = layout.getMeasuredWidth(); 
     int height = layout.getMeasuredHeight(); 
     f1.setLayoutParams(new LinearLayout.LayoutParams(width, height)); 
     f2.setLayoutParams(new LinearLayout.LayoutParams(width, height)); 
     f3.setLayoutParams(new LinearLayout.LayoutParams(width, height)); 
    } 
}); 

Проблема:

Следуя по коду, я вижу, что он устанавливает ширину и высоту каждой «секции» как ширину и высоту внешнего линейного макета. И так как это match_parent, каждый раздел имеет тот же размер, что и экран. Пока что имеет смысл. Теперь в длинном прокручиваемом списке есть 3 раздела, которые соответствуют ширине и высоте экрана. Требования говорят, что только первая секция должна соответствовать ширине и высоте экрана. Так как высота первого раздела соответствует match_parent, а две другие секции height - wrap_content. Я думаю, что удаление этих двух строк кода Java

f2.setLayoutParams(new LinearLayout.LayoutParams(width, height));
f3.setLayoutParams(new LinearLayout.LayoutParams(width, height));

должны сделать следующие 2 секции обернуть их содержание. Но на самом деле это приводит к тому, что первая секция отображается в полноэкранном режиме, но, тем не менее, прокрутка отключена, поэтому я не могу прокрутить вниз, чтобы увидеть другие разделы. Может ли кто-нибудь объяснить, что здесь происходит? И если есть лучший способ достичь того, что я пытаюсь сделать здесь, я хотел бы услышать об этом.

ответ

0

Я действительно смог заставить это работать должным образом со следующим кодом. Оказывается, это была проблема с тем, что ImageView был настроен на обертку содержимого, но поскольку не было изображения только цвета, он не должен был знать, где его можно обернуть. Но этот код работает для меня.

Layout

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" 
     xmlns:tools="http://schemas.android.com/tools" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:fillViewport="true" 
     tools:context=".MainActivity" > 

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

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

     <TextView 
      android:layout_width="wrap_content" 
      android:layout_height="0dp" 
      android:layout_weight="1" 
      android:text="top text" 
      android:layout_gravity="center_horizontal" 
      android:gravity="bottom" 
      android:paddingTop="35dp" 
      android:textColor="@android:color/holo_red_dark"/> 

     <TextView 
      android:layout_width="wrap_content" 
      android:layout_height="0dp" 
      android:layout_weight="1" 
      android:text="middle text" 
      android:layout_gravity="center_horizontal" 
      android:textColor="@android:color/holo_red_dark"/> 

     <TextView 
      android:layout_width="wrap_content" 
      android:layout_height="0dp" 
      android:layout_weight="1" 
      android:text="bottom text" 
      android:layout_gravity="center_horizontal" 
      android:gravity="bottom" 
      android:textColor="@android:color/holo_red_dark"/> 
    </LinearLayout> 

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

     <ImageView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:textColor="@android:color/holo_red_dark"/> 

     <TextView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="middle text" 
      android:layout_gravity="center_horizontal" 
      android:textColor="@android:color/holo_red_dark"/> 

     <TextView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="bottom text" 
      android:layout_gravity="center_horizontal" 
      android:gravity="bottom" 
      android:textColor="@android:color/holo_red_dark"/> 
    </LinearLayout> 

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

     <ImageView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:textColor="@android:color/holo_red_dark"/> 

     <TextView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="middle text" 
      android:layout_gravity="center_horizontal" 
      android:textColor="@android:color/holo_red_dark"/> 

     <TextView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="bottom text" 
      android:layout_gravity="center_horizontal" 
      android:gravity="bottom" 
      android:textColor="@android:color/holo_red_dark"/> 
    </LinearLayout> 
</LinearLayout> 

Java

final LinearLayout layout = (LinearLayout)findViewById(R.id.linlayout); 
    final LinearLayout f1=(LinearLayout) findViewById(R.id.f1); 
    ViewTreeObserver vto = layout.getViewTreeObserver(); 
    vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() 
    { 
     @Override 
     public void onGlobalLayout() 
     { 
      layout.getViewTreeObserver().removeOnGlobalLayoutListener(this); 
      int width = layout.getMeasuredWidth(); 
      int height = layout.getMeasuredHeight(); 

      f1.setLayoutParams(new LinearLayout.LayoutParams(width, height)); 
     } 
    }); 
Смежные вопросы