2011-08-30 30 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