代码中的布局方向

Gre*_*reg 82 android orientation android-linearlayout

我在我的应用程序中有这个代码:

LinearLayout.LayoutParams params =
    new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
Run Code Online (Sandbox Code Playgroud)

我只想将LinearLayout的方向设置为垂直.XML中的等价物是:

android:orientation="vertical"
Run Code Online (Sandbox Code Playgroud)

如果没有XML,我怎么能在代码中做到这一点?

Mic*_*ael 178

你不能LinearLayout用它改变方向LayoutParams.它只能用一个LinearLayout对象来完成.

LinearLayout layout = /* ... */;
layout.setOrientation(LinearLayout.VERTICAL);
Run Code Online (Sandbox Code Playgroud)


Bal*_*ake 6

你可以像这样使用:

LinearLayout myll = (LinearLayout) findViewById(R.id.yourLinearLayout);
myll.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT));
myll.setOrientation(LinearLayout.VERTICAL);
Run Code Online (Sandbox Code Playgroud)

  • 第二行应该是`myLayout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);` (4认同)