1

我想将我的 listView 的宽度设置为移动屏幕宽度的 40%。由于不同手机中 40% 的像素会有所不同,因此我无法在 xml 布局文件中设置宽度。有没有办法以编程方式为 listView 设置宽度

4

4 回答 4

0

实际上,您通常可以在 XML 中使用layout_weight. 有关说明,请参阅线性布局指南。要记住几件事:

  1. 确保将大小(layout_width对于水平布局,layout_height对于垂直布局)设置为0dp不会干扰动态布局。
  2. 您通常会在布局中的其他视图上设置权重,因此它们会占据剩余的 60%。但是,如果没有,您可以定义一个权重总和
于 2013-02-23T06:06:55.243 回答
0
Display display = getWindowManager().getDefaultDisplay();
int width = (display.getWidth()*40)/100;

在获得宽度后,您必须通过上面的代码获得屏幕宽度大小,您必须通过 setparam 将其设置到您的代码中。

于 2013-02-23T06:07:44.730 回答
0

您可以以编程方式获取屏幕宽度,然后获取屏幕宽度的 40% 并设置为ListView。如果您想使用 xml 执行此操作,请使用LinearLayout并设置android:weightSum为此然后使用重量。使用这种方式您可以轻松地做到这一点。

获得屏幕重量的 40%

  Display  display= ((WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
    int width = (display.getWidth()*40)/100;

在 xml 中为视图设置权​​重

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    android:orientation="vertical"
    android:weightSum="100" >
   <Button android:layout_width="wrap_content"
   android:layout_height="0dp"
   android:layout_weight="50"
   android:text="button1"/>
  <Button android:layout_width="wrap_content"
  android:layout_height="0dp"
  android:layout_weight="50"
  android:text="button2"/>
</LinearLayout>
于 2013-02-23T06:09:56.313 回答
0

您在视图及其参数方面存在概念错误。您可以以编程方式设置的不同类型的宽度,您也可以在您的 xml 布局中设置它。以编程方式将布局参数设置为视图的优势在于可以在运行时更改视图布局参数。您的问题的解决方案很简单,您只需将 listView 放入 LinearLayout 并将其权重设置为 0.4

于 2013-02-23T06:12:34.247 回答