Android CheckBox文本无法显示

Mat*_*ins 10 checkbox android android-layout

我正试图在我的一个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>
    
    Run Code Online (Sandbox Code Playgroud)
  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);
    
    Run Code Online (Sandbox Code Playgroud)

我的"真实"代码比这更复杂(任何动态),这就是我没有简单地在布局本身中包含复选框的原因.但是,即使对我的代码进行调整仍然无法正确呈现复选框文本.

这是一个演示的屏幕截图(请参阅"吸引到"部分),稍加一些,以证明我的垂直布局似乎正常工作,否则:

Android复选框缺少文字

Mat*_*ins 23

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

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);
Run Code Online (Sandbox Code Playgroud)


小智 5

您没有设置布局参数,布局参数说明控件将如何显示

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