java 以编程方式将重力设置为 Horizo​​ntalScrollView 的垂直居中内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7994058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 22:36:19  来源:igfitidea点击:

Programmatically set gravity to vertically center content of HorizontalScrollView

javaandroidandroid-layout

提问by Dynde

I have a HorizontalScrollView containing a LinearLayout. I can't seem to get the content to vertically center inside my scrollview, I can't set gravity on the horizontalscrollview, even though I tried with a LinearLayout.LayoutParams when setting the scrollview as contentview.

我有一个包含 LinearLayout 的 Horizo​​ntalScrollView。我似乎无法让内容在我的滚动视图中垂直居中,我无法在水平滚动视图上设置重力,即使我在将滚动视图设置为内容视图时尝试使用 LinearLayout.LayoutParams。

Can anyone help?

任何人都可以帮忙吗?

This is what I have:

这就是我所拥有的:

HorizontalScrollView sv = new HorizontalScrollView(c);

HorizontalScrollView sv = new HorizontalScrollView(c);

LinearLayout llh = new LinearLayout(c);llh.setOrientation(LinearLayout.HORIZONTAL);

LinearLayout llh = new LinearLayout(c);llh.setOrientation(LinearLayout.HORIZONTAL);

sv.addView(llh, llh_lp)

sv.addView(llh, llh_lp)

llh_lp is just simple wrap_content params.

llh_lp 只是简单的 wrap_content 参数。

setContentView(sv)

setContentView(sv)

And I tried adding linearlayout.layoutparams with gravity = gravity.center_vertical too, on the setContentView call.

我也尝试在 setContentView 调用中添加带有重力 = 重力.center_vertical 的 linearlayout.layoutparams。

回答by Arun Badole

Try this way..

试试这个方法。。

HorizontalScrollView sv = new HorizontalScrollView(this);
    sv.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
    LinearLayout llh = new LinearLayout(this); 
    llh.setOrientation(LinearLayout.HORIZONTAL);
    llh.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
    llh.setGravity(Gravity.CENTER_VERTICAL);
    TextView tv = new TextView(this);
    tv.setText("Policia Centeras");
    tv.setBackgroundColor(-16776961);

    llh.addView(tv);
    sv.addView(llh);
    setContentView(sv);

I hope it helps you.

我希望它能帮助你。