2011-08-30 27 views
3

我想用Java中的TextViews創建一個LinearLayout,因爲元素的數量是動態指定的,因此使用XML將無法爲我工作。 這裏是我的代碼的一個小樣本:在Java中創建LinearLayout - 元素不顯示

public class MyActivity extends Activity { 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    LinearLayout layout = new LinearLayout(this); 
    layout.setOrientation(LinearLayout.VERTICAL); 
    layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); 


    TextView titleView = new TextView(this); 
    titleView.setWidth(LayoutParams.WRAP_CONTENT); 
    titleView.setHeight(LayoutParams.WRAP_CONTENT); 
    titleView.setTextAppearance(this, android.R.attr.textAppearanceLarge); 
    titleView.setText("Hallo Welt!"); 
    layout.addView(titleView); 

    setContentView(layout); 

} 
} 

當我開始這個活動它不顯示這個TextView的,但它也沒有顯示錯誤。 有沒有人有建議?

回答

11

試試這個,

LinearLayout layout = new LinearLayout(this); 
     layout.setOrientation(LinearLayout.VERTICAL); 
     layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); 

     TextView titleView = new TextView(this); 
     LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
     titleView.setLayoutParams(lparams); 
     titleView.setTextAppearance(this, android.R.attr.textAppearanceLarge); 
     titleView.setText("Hallo Welt!"); 
     layout.addView(titleView); 

     setContentView(layout); 
+0

幹得好!這是錯誤 – Jay

0

試試這個

titleView.setWidth(100); 
titleView.setHeight(40); 

titleView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 
2
TextView titleView = new TextView(this); 
    titleView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 
    titleView.setTextAppearance(this, android.R.attr.textAppearanceLarge); 
    titleView.setText("Hallo Welt!"); 
    layout.addView(titleView); 
    setContentView(layout); 
+0

謝謝,它的工作原理! – Jay

1

使用此代碼:

LinearLayout layout = new LinearLayout(this); 
    layout.setOrientation(LinearLayout.VERTICAL); 
    layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); 

    TextView titleView = new TextView(this); 
    titleView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 
    titleView.setTextAppearance(this, android.R.attr.textAppearanceLarge); 
    titleView.setText("Hallo Welt!"); 
    layout.addView(titleView); 

    setContentView(layout); 
+0

工作很棒!謝謝! – Jay