能否不使用第三方库以屏幕百分比设置Android View的宽高?
不用第三方库实现按屏幕百分比设置View宽高
当然可以,Android原生提供了几种方案实现这个需求,不需要依赖任何第三方库:
1. 使用ConstraintLayout的百分比约束
这是最推荐的原生方案,ConstraintLayout本身支持百分比布局,步骤如下:
- 根布局采用
ConstraintLayout - 目标View的
layout_width和layout_height设为0dp(即match_constraint) - 通过
layout_constraintWidth_percent和layout_constraintHeight_percent属性设置百分比,取值范围0-1(比如70%对应0.7)
示例代码:
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="0dp" android:layout_height="0dp" app:layout_constraintWidth_percent="0.7" app:layout_constraintHeight_percent="0.8" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" android:text="百分比布局示例"/> </androidx.constraintlayout.widget.ConstraintLayout>
2. 自定义View重写onMeasure
如果不想用ConstraintLayout,可以自定义View,在onMeasure方法中根据屏幕尺寸计算目标宽高:
public class PercentTextView extends TextView { private float widthPercent = 0.7f; private float heightPercent = 0.8f; public PercentTextView(Context context) { super(context); } public PercentTextView(Context context, AttributeSet attrs) { super(context, attrs); // 可通过自定义属性传入百分比,此处为简化处理 } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { DisplayMetrics metrics = getContext().getResources().getDisplayMetrics(); int screenWidth = metrics.widthPixels; int screenHeight = metrics.heightPixels; int targetWidth = (int) (screenWidth * widthPercent); int targetHeight = (int) (screenHeight * heightPercent); setMeasuredDimension(targetWidth, targetHeight); } }
布局中直接使用该自定义View:
<com.yourpackage.PercentTextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="自定义View百分比示例"/>
3. 使用LinearLayout的weight属性(单维度百分比)
如果是在LinearLayout中,可以利用layout_weight实现单一方向的百分比控制(宽或高,取决于LinearLayout的orientation):
- 给LinearLayout设置
weightSum="100" - 目标View对应方向的尺寸设为
0dp,并设置layout_weight为百分比数值(比如70)
示例(横向布局下设置宽度70%):
<LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:weightSum="100"> <TextView android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="70" android:text="LinearLayout百分比宽度示例"/> </LinearLayout>
注意:这种方法只能控制一个方向的尺寸,灵活性不如ConstraintLayout。
内容的提问来源于stack exchange,提问作者Love Credit
相关产品推荐
相关产品推荐

