在Java中创建LinearLayout - 未显示元素

时间:2011-08-30 09:27:20

标签: java android view android-linearlayout

我正在尝试使用Java中的TextViews创建一个LinearLayout,因为动态指定了元素的数量,因此使用XML将无法解决问题。 以下是我的代码的一些示例:

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,但它也不显示错误。 有没有人有建议?

4 个答案:

答案 0 :(得分:13)

试试这个,

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

答案 1 :(得分: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);

答案 2 :(得分: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);

答案 3 :(得分:0)

试试这个

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

   titleView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));