【问题标题】:android change button size according to device screen sizeandroid根据设备屏幕大小更改按钮大小
【发布时间】:2016-04-22 03:53:49
【问题描述】:

我想将我的应用程序设计调​​整到任何 android 设备,我已经尝试按百分比设置元素大小属性,但我用这种方式遇到了麻烦,所以我尝试了这个代码:(按设备屏幕大小设置宽度和高度 / 5 )

public void fixButtonSizes (){
    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    int width1 = size.x;
    int height1 = size.y;
    Button button1vid = (Button) findViewById(R.id.button1);
    button1vid.setHeight(height1 / 5);
    button1vid.setWidth(width1 / 5);
}

它对我也不起作用

【问题讨论】:

标签: android height size width


【解决方案1】:

要在 android 中使用百分比宽度或高度,您应该将元素包裹在 LinearLayout 中并使用元素的 layout_weight 属性。您还必须根据您想要的尺寸将0dp 放入layout_widthlayout_width

要计算一个元素的高度或宽度,你必须将布局中所有元素的 layout_weight 相加,然后除以元素的权重。

例如,如果你想在水平方向上创建一个宽度相同的 5 个按钮,你可以使用这个:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Button 1"/>

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Button 2"/>

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Button 3"/>

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Button 4"/>

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Button 5"/>

</LinearLayout>

我希望这能澄清你。

【讨论】:

  • 我对这行代码有一些问题:android:layout_width="0dp" 它说它将是不可见的
  • 您是否将所有视图包装在 LinearLayout 中并添加了 android:layout_weight="1"??
  • 是的,我想说我有更多的线性布局,但是这个特定的布局就像你让我定义的那样定义
  • 你可以发布布局吗?
  • 我发现问题在于我在线性布局属性中放置了这条线 android:orientation="vertical" 并且当我删除它时它解决了问题但我想要这个方向用于我的设计那我怎么能两者兼得
猜你喜欢
  • 1970-01-01
  • 2020-08-14
  • 2016-08-28
  • 2017-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多