在 Java 中创建 LinearLayout - 元素未显示 [英] Creating LinearLayout in Java - Elements are not shown

查看:35
本文介绍了在 Java 中创建 LinearLayout - 元素未显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Java 中的 TextViews 创建一个 LinearLayout,因为元素的数量是动态指定的,所以使用 XML 对我来说不起作用.这是我的代码的一个小示例:

I am trying to create a LinearLayout with TextViews in Java, because the number of elements is dynamically specified so using XML won't work out for me. Here is a little sample of my Code:

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,但也不会显示错误.有人给点建议吗?

When i start this activity it does not show this TextView but it also does not show an error. Does anyone have an advice?

推荐答案

试试这个,

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

这篇关于在 Java 中创建 LinearLayout - 元素未显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆