请考虑下图:
蓝色按钮是按钮,红色按钮是textview。我试图将它们如图所示并排放置,但是由于应用程序应该与不同的屏幕尺寸和密度兼容而感到困惑。
基本上,我希望所有按钮都具有相同的大小(通常为正方形),并且TextView
更大,并说当屏幕变大(例如旋转)时,只有中间(红色)textView应该扩展,按钮大小应该是他们在自己的位置上保持一致。
我尝试了什么
LinearLayout
并设置了layout_weight
,但对于更大的屏幕尺寸,按钮(蓝色)也将放大占其布局重量的比例,并且看起来不像正方形。 constraint layout
这样做很容易,但是,这需要硬编码按钮的大小(在设计编辑器中调整按钮的大小这样做),我认为这不是一个好主意,因为如果屏幕变大,按钮将变小。 我也可以采用一定比例的屏幕宽度并将其应用于按钮大小,但是如何确保按钮的图标与缩放后的按钮一样好并且按钮按以下方式对齐:
即它们的中心对齐,但高度不同,彼此等距。我也必须以编程方式执行此操作,而不是使用设计编辑器或xml。
因此,出于这种目的,我应该使用哪种布局以及如何设置视图?
使用linear layout
,仅对layout_weight
使用TextView
,对于Buttons
给出固定宽度例如
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_height="match_parent">
<Button
android:layout_width="@dimen/length_50"
android:background="@color/colorPrimary"
android:layout_height="@dimen/length_50"/>
<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:background="@color/colorAccent"
android:layout_height="@dimen/length_50"/>
<Button
android:layout_width="@dimen/length_50"
android:layout_marginEnd="@dimen/_10dp"
android:background="@color/colorPrimary"
android:layout_height="@dimen/length_50"/>
<Button
android:layout_width="@dimen/length_50"
android:layout_marginEnd="@dimen/_10dp"
android:background="@color/colorPrimary"
android:layout_height="@dimen/length_50"/>
<Button
android:layout_width="@dimen/length_50"
android:background="@color/colorPrimary"
android:layout_height="@dimen/length_50"/>
</LinearLayout>
和结果