假设如果我设置水平方向线性布局,那么匹配父项的总像素应该是多少,以便我可以根据该大小调整我的按钮和文本视图。
我试图放置所有边距并计算...
预期的输出将取决于屏幕尺寸。
视图的总像素match_parent取决于parentView布局中视图的类型、尺寸和组成,例如,如果您parentView的LinearLayout尺寸足够大,100px * 100px那么您match_parent在其中的视图LinearLayout是100px * 100px(如果您只有一个视图,LinearLayout否则取决于您的合成)您可以通过将以下代码用于任何height或widthviewLayout
爪哇
view.post(new Runnable(){
@Override
public void run() {
int height = view.getMeasuredHeight();
int width = view.getMeasuredWidth();
}
});
科特林
view.post {
val width = view.measuredWidth
val height = view.measuredHeight
}
获得布局的高度和宽度后,您可以根据您的逻辑管理边距或大小
的总像素match parent是屏幕大小的总像素,如果您要为视图实现自动调整大小,您应该将其constraint layout用作视图的父布局,或者使用这个使用名为sdp https 的新大小单位的优秀库: //github.com/intuit/sdp
不要使用像素,它会使您的屏幕无法响应所有屏幕尺寸。如果您希望屏幕响应所有屏幕尺寸,请使用ConstraintLayout或相对布局。
这是一个视图示例,他的宽度与使用 ConstraintLayout 的所有屏幕尺寸相等:
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:id="@+id/button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>