【问题标题】:Buttons in linearlayout appearing vertically instead of horizontally?线性布局中的按钮垂直而不是水平出现?
【发布时间】:2013-09-30 18:07:44
【问题描述】:

我对 Android 很陌生,我正在尝试在我的 Android 应用程序中动态添加按钮,问题是它们是垂直显示的,而这应该是水平显示的。

我得到了什么:

我期待(和想要的):

我正在使用的代码:

MainActivity.java:

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    LinearLayout ll = (LinearLayout)findViewById(R.id.main_linearlayout);

    for(int x = 1; x <= 5 ; x++)
    {
        LinearLayout tmpLinearLayout = new LinearLayout(this);
        tmpLinearLayout.setOrientation(LinearLayout.VERTICAL);
        tmpLinearLayout.setLayoutParams( new LinearLayout.LayoutParams(
                LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT, 1.0f));
        tmpLinearLayout.getLayoutParams().height = 200;
        ll.addView(tmpLinearLayout); 

        for(int i = 0;i<5;i++)
        {

            Button tmpButton = new Button(this);
            tmpButton.setText("nr:" + i +" - " + x);

            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT, 1.0f);

            tmpLinearLayout.addView(tmpButton, lp);
        }
    }
}

布局(activity_main.xml):

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:id="@+id/main_linearlayout"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" 
    android:background="@drawable/background"
    android:orientation="horizontal" >
</LinearLayout>

谁能解释为什么会这样/纠正我? 谢谢!

【问题讨论】:

  • 当 android:orientation = "horizo​​ntal" 在你的 xml 布局中,那么它将如何显示垂直视图。只需将其更改为垂直。然后所有内容都将调整为垂直。

标签: java android


【解决方案1】:

您正在以编程方式设置垂直方向。-

替换此行

tmpLinearLayout.setOrientation(LinearLayout.VERTICAL);

这个

tmpLinearLayout.setOrientation(LinearLayout.HORIZONTAL);

PS:据我所知,Horizontal 是默认方向,所以你实际上可以删除方向线。

【讨论】:

  • 同意。虽然看起来很明显
  • 现在它们都出现在彼此旁边。您知道如何修复它以保持当前布局(5x5 表)吗?谢谢!
  • 您希望在 XML 中是垂直的,而在代码中是水平的。确保你改变了它们。
  • @JessicaSmets 使用 5 列按钮的网格视图
  • 我试试看,你!
【解决方案2】:

在您的 xml 布局中将 android:orientation 更改为 vertical

【讨论】:

    最近更新 更多