在 Android 2.3.3 中开发的应用程序
我正在开发一个计算器应用程序。
问题 1::: 我有大约 16 个按钮。有没有一种方法可以使用循环(或)不使用它来设置所有按钮的宽度和高度。我希望所有按钮都统一。
问题 2::: 您如何看待这种做法?是好是坏?请解释为什么? 假设我每行有 4 个按钮。如果我以编程方式获取屏幕的宽度和高度,然后除以 (width/4) 并为每个按钮添加边距,然后分别设置按钮的宽度 (width/4 + margin),这是否会以某种方式解决问题在不同尺寸的屏幕上显示?
最佳答案
根据设备的宽度和高度平均提供 View 的宽度或高度的最佳方法是使用权重属性,举个例子,我们有一个线性布局,有四个按钮,宽度相等:
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button android:layout_width="0dip"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="button1"/>
<Button android:layout_width="0dip"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="button2"/>
<Button android:layout_width="0dip"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="button3"/>
<Button android:layout_width="0dip"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="button4"/>
</LinearLayout>
但是,如果您仍然想在运行时提供布局宽度和高度,您可以使用 setLayoutParams(new LayoutParams(100, 100));
方法。
关于android - 以编程方式设置组件的宽度和高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13737786/