以编程方式设置组件的宽度和高度

Vam*_*lla 3 android

在Android 2.3.3中开发的应用程序

我正在开发计算器应用程序.

问题1 :::我有大约16个按钮.有没有一种方法可以在没有它的情况下使用循环(或)来设置所有按钮的宽度和高度.我希望所有的按钮都是统一的.

问题2 :::您如何看待这种做法?是好是坏?请解释原因?假设我每行有4个按钮.如果我以编程方式获得屏幕的宽度和高度,然后除以(宽度/ 4)并为每个按钮添加边距,然后分别设置按钮的宽度(宽度/ 4 +边距),这将以某种方式解决问题在不同尺寸的屏幕上显示?

jee*_*eet 5

根据设备宽度和高度同等地提供视图宽度或高度的最佳方法是使用权重属性,举个例子,我们有一个线性布局,有四个宽度相等的按钮:

<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>
Run Code Online (Sandbox Code Playgroud)

但是,如果您仍希望在运行时提供布局宽度和高度,则可以使用setLayoutParams(new LayoutParams(100, 100));方法.