【问题标题】:make check boxes the same size使复选框大小相同
【发布时间】:2014-07-24 15:52:14
【问题描述】:

我的一个屏幕包含布局文件中预定义的复选框和以编程方式添加的复选框。问题是它们的尺寸不同。

布局文件中定义的最终会显示一个更大的方框;勾选后,勾选标记为绿色(看起来正常):

<CheckBox
        android:id="@+id/foo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="5dip"
        android:text="foo text"
        android:textColor="@color/Black"
        android:checked="false" />

在代码中创建的,不仅有一个小得多的方框,而且还有更暗的边框;选中时,复选标记为蓝色(看起来很奇怪):

        CheckBox checkbox = new CheckBox(getApplicationContext());
        checkbox.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        checkbox.setText(innerData.getType_description());
        checkbox.setTextColor(getResources().getColor(R.color.Black));
        somelinearlayout.addView(checkbox); 

如何修改代码以使所有复选框具有相同的外观?

【问题讨论】:

  • 不要使用wrap content,而是使用match parent..
  • 感谢回复,还是一样。
  • 你可以使用 CheckBox checkbox = new CheckBox(getApplicationContext(), your attri. , any style);

标签: android checkbox


【解决方案1】:

我建议不要以编程方式创建 CheckBox,而是将它们膨胀。可能有点贵,但是您可以从父 ViewGroup 获得正确的 LayoutParams,并且您可以更轻松地设置膨胀 CheckBox 的样式(因为它是在 xml 布局中)。示例代码如下:

“my_checkbox”xml 布局

<?xml version="1.0" encoding="utf-8"?>
<CheckBox xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</CheckBox>

活动布局

// excerpt from the activity layout
<LinearLayout
    android:id="@+id/checkbox_container"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="CB 1" />

    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="CB 2" />
</LinearLayout>

活动类

// Excerpt from the Activity
private TextView targetTextView;
private ViewGroup checkboxContainer;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    checkboxContainer = (ViewGroup) findViewById(R.id.checkbox_container);
    CheckBox checkbox3 = (CheckBox) getLayoutInflater().inflate(R.layout.my_checkbox, checkboxContainer, false);
    checkbox3.setText("Inflated Checkbox");
    checkboxContainer.addView(checkbox3);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-13
    • 1970-01-01
    • 2011-07-26
    • 1970-01-01
    • 1970-01-01
    • 2011-03-14
    • 1970-01-01
    相关资源
    最近更新 更多