2011-10-07 74 views
10

我想在我的Android活动之一中动态创建一些复选框,但它不会呈现文本。Android复选框文本不显示

这里是我的简化代码...

  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); 
    

我的 “真实” 的代码是比这更复杂(任何动态),这是为什么我没有简单地在布局中包含复选框。然而,即使是瘫痪我的代码仍然不能正确显示复选框文本。

这里有一个截图来证明(见“吸引到”一节),有一点点额外的证明,我的垂直布局表现为正常工作,不然:

Android checkboxes missing text

+0

我不会动态地添加用户界面组件,因为在开发时很难查看它们。开发人员需要运行整个应用程序才能看到添加的组件。我虚心建议增加他们的能见度消失了。它非常轻便,因为它们从来没有绘制过,但仍然可以找到(findViewById)。 –

+1

复选框通过HttpRequest生成,这意味着您的建议是不可能的。 –

回答

21

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

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); 
+1

这也发生在我身上。似乎复选框的默认文本颜色在预蜂窝设备上是白色的 –

+0

年,就像文本视图一样 –

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); 
+0

我以前试过这样做,这对我不起作用:'male.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));'尽管我一会儿就会尝试你的解决方案。 –

+0

它看起来像复选框只接受'ViewGroup.LayoutParams',并没有第三个参数为这个构造函数,因为你在这里提供。我尝试了每个使用'LayoutParams.WRAP_CONTENT'的双参数构造函数,并且这也不起作用。 –

+0

但你的代码完全适合我 – jazz

0

也许这是由于简化了您的真实代码,但您是否设置了复选框的宽度和高度?

+0

请参阅我的评论[@ jazz's response](http://stackoverflow.com/questions/7689475/android-checkbox-text-not-displaying/7689533#7689533)。 –