PercentRelativeLayout внутри ScrollView

Я создал макет, используя ScrollView, который имеет PercentRelativeLayout в качестве своего дочернего элемента. Он не работает на Lollipop и более старых устройствах, но отлично работает на устройствах Marshmallow. Проверьте код ниже:

<ScrollView
    android:id="@+id/scrollView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">

    <android.support.percent.PercentRelativeLayout
        android:id="@+id/scrollContent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_heightPercent="100%"
        app:layout_widthPercent="50%">

        <TextView
            android:id="@+id/textView1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/holo_red_dark"
            android:text="kkjknadko"
            android:textColor="@android:color/black"
            app:layout_heightPercent="10%"
            app:layout_widthPercent="50%"/>

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/textView1"
            android:text="Abcaad"
            android:textColor="@android:color/black"
            app:layout_heightPercent="10%"
            app:layout_marginTopPercent="10%"
            app:layout_widthPercent="50%"/>

        <TextView
            android:id="@+id/textview3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/textview2"
            android:background="@android:color/holo_red_dark"
            android:text="Abcd"
            android:textColor="@android:color/black"
            app:layout_heightPercent="10%"
            app:layout_marginTopPercent="10%"
            app:layout_widthPercent="50%"/>

        <TextView
            android:id="@+id/textview4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/textview3"
            android:text="Abcd"
            android:textColor="@android:color/black"
            app:layout_heightPercent="10%"
            app:layout_marginTopPercent="10%"
            app:layout_widthPercent="50%"/>

        <TextView
            android:id="@+id/textview5"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/textview4"
            android:background="@android:color/holo_red_dark"
            android:text="Abcd"
            android:textColor="@android:color/black"
            app:layout_heightPercent="10%"
            app:layout_marginTopPercent="10%"
            app:layout_widthPercent="50%"/>

        <TextView
            android:id="@+id/textview6"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/textview5"
            android:text="Abcd"
            android:textColor="@android:color/black"
            app:layout_heightPercent="10%"
            app:layout_marginTopPercent="10%"
            app:layout_widthPercent="50%"/>

        <TextView
            android:id="@+id/textview7"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/textview6"
            android:text="Abcd"
            android:textColor="@android:color/black"
            app:layout_heightPercent="10%"
            app:layout_marginTopPercent="10%"
            app:layout_widthPercent="50%"/>

        <TextView
            android:id="@+id/textview8"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/textview7"
            android:text="Abcd"
            android:textColor="@android:color/black"
            app:layout_heightPercent="10%"
            app:layout_marginTopPercent="10%"
            app:layout_widthPercent="50%"/>

    </android.support.percent.PercentRelativeLayout>
</ScrollView>

А также я android:fillViewport="true", он ничего не показывает в версиях Lollipop и старше Android.

К сожалению, процентный макет не будет работать с ScrollView до M. Причина этого в том, что они зависят от подсказки размера, которая доставляется на этапе измерения. До M большинство макетов обеспечивали подсказку размера 0 при отправке спецификации неопределенной меры.

Вы можете исправить это, создав свой собственный подкласс ScrollViewи переопределение measureChild и measureChildWithMargins(к счастью, оба они защищены), чтобы предоставить подсказку размера.

source - plus.google.com.

Может ли кто-нибудь помочь мне создать пользовательский ScrollView, чтобы он работал?

Ответы

Ответ 1

Создайте один настраиваемый scrollview и установите Measured Height и Width, как вы хотите, для примера

CustomScrollView

public class CustomScrollView extends ScrollView {


    public CustomScrollView(Context context) {
        super(context);
    }

    public CustomScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public CustomScrollView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int size = 0;
        int width = getMeasuredWidth();
        int height = getMeasuredHeight();

        if (width > height) {
            size = height;
        } else {
            size = width;
        }
        setMeasuredDimension(size, size);
    }
}

Используйте customcrollview в xml.

    <yourscrollviewclasspath.CustomScrollView           // here you have scrollview path like com.yourpackage.folder_where_your_scrollview_lies
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/scrollView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true"
        >
</yourscrollviewclasspath.CustomScrollView >

введите описание изображения здесь надеюсь, это поможет.

Ответ 2

Вопрос, как я понимаю, это: я хочу, чтобы эти TextViews составляли 50% ширины родительского представления.

Способ, который работает для меня, это:

<Space
    android:layout_width="20dp"
    android:layout_height="20dp"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:id="@+id/space" />

Затем сопоставьте View (s) с этим. Либо RelativeLayout, либо TextViews. Вы теряете контроль (если он когда-либо был) над процентом RelativeLayout. Я имею тенденцию идти с такими вещами, как:

    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"

Помогает ли это?

Ответ 3

Я столкнулся с той же проблемой с android K и android L.

Вы могли бы использовать компоновку ограничений вместо процента относительного макета, но, похоже, проблема с прокруткой тоже. Даже пользовательский просмотр прокрутки, предложенный в других ответах, не помог мне.

Хотя есть способ.

Преобразуйте процентный относительный макет в относительный макет и программно установите высоту представлений в соответствии с высотой вашего устройства.

В прокрутке с относительной компоновкой нет проблем. И вы можете использовать представление "Пробел" для поля между TextViews. Это не очень изящное решение, но для меня это сработало.

Код Java:

int height = getWindowManager().getDefaultDisplay().getHeight();
int width = getWindowManager().getDefaultDisplay().getWidth();

// to set height to each textview to 10% of screen
textView1.getLayoutParams().height = (int) (height * 0.10);
textView2.getLayoutParams().height = (int) (height * 0.10);
textView3.getLayoutParams().height = (int) (height * 0.10);
textView4.getLayoutParams().height = (int) (height * 0.10);
textView5.getLayoutParams().height = (int) (height * 0.10);
textView6.getLayoutParams().height = (int) (height * 0.10);

// to set width to each textview to 50% of screen
textView1.getLayoutParams().width = (int) (width * 0.50);
textView2.getLayoutParams().width = (int) (width * 0.50);
textView3.getLayoutParams().width = (int) (width * 0.50);
textView4.getLayoutParams().width = (int) (width * 0.50);
textView5.getLayoutParams().width = (int) (width * 0.50);
textView6.getLayoutParams().width = (int) (width * 0.50);

// for margin between textviews
space1.getLayoutParams().height = (int) (height * 0.10);
space2.getLayoutParams().height = (int) (height * 0.10);
space3.getLayoutParams().height = (int) (height * 0.10);
space4.getLayoutParams().height = (int) (height * 0.10);
space5.getLayoutParams().height = (int) (height * 0.10);

Код XML:

<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">

<RelativeLayout
    android:id="@+id/scrollContent"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_red_dark"
        android:text="kkjknadko"
        android:textColor="@android:color/black"/>

    <android.support.v4.widget.Space
        android:id="@+id/space1"
        android:layout_below="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/space1"
        android:text="Abcaad"
        android:textColor="@android:color/black"/>

    <android.support.v4.widget.Space
        android:id="@+id/space2"
        android:layout_below="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/space2"
        android:background="@android:color/holo_red_dark"
        android:text="Abcd"
        android:textColor="@android:color/black"/>

    <android.support.v4.widget.Space
        android:id="@+id/space3"
        android:layout_below="@+id/textView3"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/space3"
        android:text="Abcd"
        android:textColor="@android:color/black"/>

    <android.support.v4.widget.Space
        android:id="@+id/space4"
        android:layout_below="@+id/textView4"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content" />

    <TextView
        android:id="@+id/textview5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/space4"
        android:background="@android:color/holo_red_dark"
        android:text="Abcd"
        android:textColor="@android:color/black"/>

    <android.support.v4.widget.Space
        android:id="@+id/space5"
        android:layout_below="@+id/textview5"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content" />

    <TextView
        android:id="@+id/textview6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/space5"
        android:text="Abcd"
        android:textColor="@android:color/black"/>

</RelativeLayout>