LinearLayout仅允许添加一个视图

时间:2011-11-23 04:35:57

标签: android android-layout

  layout = new LinearLayout(this);
            addContentView(layout, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));


            Button btn = new Button(this);
            btn.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
           btn.setText("button");

            layout.addView(btn);

            Button btn1 = new Button(this);
            btn1.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
           btn1.setText("button");

            layout.addView(btn1);

我知道我必须遗漏一些东西,因为每当我为这个布局添加视图时,我只会显示其中一个。

3 个答案:

答案 0 :(得分:2)

享受好友

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

重申此addContentView(layout, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

您尚未设置Oreientation,默认为水平,并且您已指定宽度LayoutParams.FILL_PARENT

答案 1 :(得分:1)

 layout = new LinearLayout(this);
layout .setOrientation(LinearLayout.VERTICAL); // orientation vertical try  this

            addContentView(layout, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));


            Button btn = new Button(this);
            btn.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
           btn.setText("button");

            layout.addView(btn);

            Button btn1 = new Button(this);
            btn1.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
           btn1.setText("button");

            layout.addView(btn1);

答案 2 :(得分:1)

线性布局的方向必须是水平的。将其更改为垂直