如何在 PercentRelativeLayout 中使百分比动态化?

How to make Percent dynamic in PercentRelativeLayout?

我正在使用设计支持库中的 PercentRelativeLayout,我想为 7 英寸和 10 英寸平板电脑设置不同的百分比。

例如,如果我有如下 ImageView

<ImageView
     android:id="@+id/contactDoc"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     app:layout_widthPercent="70%"
     app:layout_heightPercent="70%"
     android:layout_centerHorizontal="true"
     android:clickable="true"
     android:src="@drawable/dashboard_contactdoctor" />

现在,如果我想为 7 英寸平板电脑设置 70%,为 10 英寸平板电脑设置 60%,而不创建不同的布局文件夹,如 sw720dp。我可以做吗? 感谢帮助。

您可以针对不同的屏幕尺寸使用不同的布局。您可以在文档中阅读更多相关信息:https://developer.android.com/training/multiscreen/screensizes.html

一种不提供多种布局的可能性是将 ImageView 放在 LinearLayout 中,android:weightSum 为 10,然后以编程方式设置 ImageView 的权重:

LinearLayout.LayoutParams layoutParams = yourView.getLayoutParams();
layoutParams.weight = WHATEVER;
yourView.setLayoutParams(layoutParams);

尝试使用 constraint layout,它在 android studio 2.2 及更高版本上可用。

通过使用它,您可以根据屏幕百分比添加垂直和水平参考线,然后根据这些参考线设置 imageview 的高度和宽度

这些百分比是 fraction 资源。您应该能够设置 res/values/fractions.xmlres/values-sw720dp/fractions.xml,其中 define the values for the fractions。然后,在布局中使用@fraction/whatever_you_called_it

首先,您需要检测 7" 或 10" 平板电脑。我假设您已经根据您的问题知道如何去做。如果没有,请查看 this great answer

在你知道你正在处理的是什么设备之后,使用下面的代码放入一个 if 条件(或其他地方)来定义代码中视图的百分比:

    View view = findViewById(R.id.yourView);
    PercentLayoutHelper.PercentLayoutParams params =
            (PercentRelativeLayout.LayoutParams) view.getLayoutParams();
    PercentLayoutHelper.PercentLayoutInfo info = params.getPercentLayoutInfo();
    info.heightPercent = 0.60f;
    view.requestLayout();

基于