【问题标题】:Android CheckBox text not displayingAndroid CheckBox 文本不显示
【发布时间】:2011-12-03 02:52:10
【问题描述】:

我正在尝试在我的一个 Android 活动中动态创建一些 CheckBox,但它没有呈现文本。

这是我的简化代码...

  1. 布局 XML:

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="10dip">
    
        ...
        <LinearLayout
            android:id="@+id/register_attracted_to"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" />
        ...
    </LinearLayout>
    
  2. 活动代码:

    final LinearLayout attractedTo = (LinearLayout) findViewById(R.id.register_attracted_to);
    
    final CheckBox male = new CheckBox(this);
    male.setText("Male");
    attractedTo.addView(male);
    
    final CheckBox female = new CheckBox(this);
    female.setText("Female");
    attractedTo.addView(female);
    

我的“真实”代码比这更复杂(任何动态),这就是为什么我没有简单地将复选框包含在布局本身中的原因。但是,即使简化我的代码仍然无法正确呈现复选框文本。

这是一个演示屏幕截图(请参阅“吸引到”部分),还有一些额外的内容可以证明我的垂直布局似乎可以正常工作:

【问题讨论】:

  • 我不会动态添加 UI 组件,因为在开发时审查它们有困难。开发人员需要运行整个应用程序才能看到添加的组件。我谦虚地建议在可见性消失的情况下添加它们。它非常轻量级,因为它们从不被绘制,但仍然可以找到(findViewById)。
  • 复选框是通过 HttpRequest 生成的,这意味着您的建议是不可能的。

标签: android android-layout checkbox


【解决方案1】:

你没有设置布局参数,布局参数说明了控件的显示方式

final CheckBox female = new CheckBox(this);
female.setText("Female");
female .setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));
attractedTo.addView(female);

【讨论】:

  • 我之前尝试过这样做,但对我不起作用:male.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); 我会尽快尝试您的解决方案。
  • 看起来复选框只接受ViewGroup.LayoutParams,并且此构造函数没有第三个参数,正如您在此处提供的那样。我尝试了使用LayoutParams.WRAP_CONTENT 的双参数构造函数,但也没有用。
  • 不适合我。我整个周末都在玩弄它,但在我的模拟器和手机上都无济于事。
【解决方案2】:

也许是因为你的真实代码的简化,但是你设置了复选框的宽度和高度吗?

【讨论】:

【解决方案3】:

当然,我在发布赏金后不久就知道了这一点。 ;) 事实证明,由于我将容器视图的背景颜色设置为白色,因此默认的白色文本正在混合。解决方案是设置每个复选框的文本颜色。即:

final LinearLayout attractedTo = (LinearLayout) findViewById(R.id.register_attracted_to);

final CheckBox male = new CheckBox(this);
male.setText("Male");
male.setTextColor(getResources().getColor(R.color.foreground_text));
attractedTo.addView(male);

final CheckBox female = new CheckBox(this);
female.setText("Female");
female.setTextColor(getResources().getColor(R.color.foreground_text));
attractedTo.addView(female);

【讨论】:

  • 这也发生在我身上。在 pre-honeycomb 设备上,复选框的默认文本颜色似乎是白色
  • 是的,就像文本视图
【解决方案4】:

我只是做了同样的事情,发现我在initialisation code 中使用了setText("") 而不是setChecked(false)。杜!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-14
    • 1970-01-01
    • 2015-07-25
    • 2017-09-25
    • 1970-01-01
    • 2015-06-11
    相关资源
    最近更新 更多