2011-10-07 103 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)。 –