【问题标题】:How to make Button square and resizable如何使按钮方形和可调整大小
【发布时间】:2013-06-13 03:11:53
【问题描述】:

我想将按钮(其他两个按钮之间的那个)做成方形。

我尝试使用以下代码:

toggleButton = (ToggleButton) findViewById(R.id.activity_dictionary_toggleButton1);
LinearLayout.LayoutParams toggleButtonLayoutParams = (LayoutParams) toggleButton.getLayoutParams(); 
toggleButtonLayoutParams.width = toggleButtonLayoutParams.height;
toggleButton.setLayoutParams(toggleButtonLayoutParams);

但它不起作用(按钮看起来像上图)。这是我的 XML 文件的一部分:

<LinearLayout
    android:id="@+id/activity_dictionary_linearLayout2"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_marginTop="5dp" >

    <Button
        android:id="@+id/activity_dictionary_button1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical|center_horizontal"
        android:layout_weight="0.4"
        android:enabled="false"
        android:maxWidth="200dp"
        android:text="Clear"
        android:textColor="@android:color/white" />

    <ToggleButton
        android:id="@+id/activity_dictionary_toggleButton1"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_gravity="center_vertical|center_horizontal"
        android:layout_weight="0.2"
        android:background="@drawable/settings"
        android:text="ToggleButton" />

    <Button
        android:id="@+id/activity_dictionary_button2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical|center_horizontal"
        android:layout_weight="0.4"
        android:enabled="false"
        android:maxWidth="200dp"
        android:text="Recognize"
        android:textColor="@android:color/white" />

</LinearLayout>

我应该改变什么?

更新:android:layout_weight="0.2" 已删除,但当我尝试通过代码进行操作时,Button 的大小仍然没有改变(它是圆形但非常小)。

【问题讨论】:

    标签: java android android-layout android-button layoutparams


    【解决方案1】:

    您应该将 LinearLayout 切换为 RelativeLayout。您的尺寸参数应该会生效。

    【讨论】:

    • 但是父Layout是LinearLayout。为什么要切换到RelativeLayout?它正在工作,但我不明白为什么......
    • 请原谅我没有最专业的答案。当您尝试将事物组合在一起并且希望它们在所有类型的屏幕上具有相同的显示时,LinearLayouts 效果最佳。您实际上想设置高度和宽度,因此线性布局并不是最好的选择。相对布局没有这些参数,实际使用的是你设置的高度和宽度。如果您想要更多技术定义,我建议您查看开发人员说明developer.android.com/reference/android/widget/…;
    • 我感到困惑的是,我认为您必须始终使用父级的 LayoutParameters。对于我的 Button,父级是 LinearLayout。为什么编辑器不显示错误?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-30
    • 2021-09-20
    • 2011-05-30
    • 1970-01-01
    • 1970-01-01
    • 2014-12-28
    相关资源
    最近更新 更多