PercentLayoutInfo始终返回null Android

时间:2018-05-04 16:13:12

标签: android android-percent-layout

我尝试了以下代码来实现' width' (百分比)到TextView。但我总是为PercentLayoutInfo获取null。请帮忙。

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 个答案:

答案 0 :(得分:0)

我已通过在XML中将Text相关属性添加到TextView来解决此问题,如下所示。根据我的理解,我们必须在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值不是空值。