PercentLayoutInfo всегда возвращает нулевой Android

Я пробовал следующий код для реализации "ширина" (в процентах) для TextView. Но я всегда получаю нулевое значение для PercentLayoutInfo. Пожалуйста помоги.

PercentRelativeLayout.LayoutParams lp = (PercentRelativeLayout.LayoutParams) textView.getLayoutParams();

        // This will currently return null, if it was not constructed from XML.
PercentLayoutHelper.PercentLayoutInfo info = lp.getPercentLayoutInfo();

info.widthPercent = .5f;
textView.requestLayout();

Вот мой XML-файл:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/content_tile_main_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clickable="false"
    android:duplicateParentState="true"
    android:focusable="false">

    <ImageView
        android:id="@+id/main_background"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop" />

    <android.support.percent.PercentRelativeLayout
        android:id="@+id/percent_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
       >

        <TextView
            android:id="@+id/title_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:text="Title: " />
    </android.support.percent.PercentRelativeLayout>


</RelativeLayout>

1 ответ

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

 <TextView
            android:id="@+id/title_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            app:layout_widthPercent="50%"
            android:text="Title: " />

Теперь я получаю не нулевое значение для PercentLayoutInfo .

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