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

Jay*_*Jay 5 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);

}
}
Run Code Online (Sandbox Code Playgroud)

当我开始此活动时,它不会显示此TextView,但它也不会显示错误.有没有人有建议?

Lal*_*ani 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);
Run Code Online (Sandbox Code Playgroud)