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

标签 android

在 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/

相关文章:

android - android 中的 ScrollView 与 ListView

java - 编译在 Android Studio 中使用的 GitHub 项目

android - 游戏在不同时间强制关闭。需要帮助解释 logCat 警告和错误

android - 创建自己的 OnItemClickListener

android - Gradle 动态 flavor

Android Studio 自定义 ListView 滚动缓慢并导致应用程序停止

android - 使 String 资源中的 phoneNumber 在对话框中可单击

android - 如何获取所有号码的联系人?我做错了什么?

python - 使用 chaquopy 将 BeautifulSoup 实现到 Android Studio

android - 为 ListView 设置字体