[英]Android - Set Layout_Gravity programmatically for LinearLayout
I've got the following problem: I implemented a HorizontalScrollView
which contains in one case a LinearLayout
and an ImageView
. 我有以下问题:我实现了一个HorizontalScrollView
,其中包含一个LinearLayout
和一个ImageView
。 In this case the image is about 50% of the screen width. 在这种情况下,图像大约是屏幕宽度的50%。 So I want to center it. 所以我想把它集中在一起。 Unfortunately the only way I found to center it is, to use layout_gravity="center"
on the LinearLayout
. 不幸的是,我发现它的唯一方法就是在LinearLayout
上使用layout_gravity="center"
。
Here's my xml: 这是我的xml:
<HorizontalScrollView
android:layout_gravity="center"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:src="@drawable/myImg"
android:layout_width="wrap_content"
android:adjustViewBounds="true"
android:layout_height="150dp"/>
</LinearLayout>
</HorizontalScrollView>
But I need to set the layout_gravity
programmatically. 但我需要以编程方式设置layout_gravity
。 Does anybody has an idea how I can achieve this or knows a different way? 有没有人知道如何实现这一目标或知道不同的方式? All the things I found via Google are not working for me like this post . 我通过Google发现的所有内容都不适用于我这样的帖子 。
Thanks! 谢谢!
Do somethings like this : 做这样的事情:
LayoutParams lp = new LayoutParams();
lp.gravity= Gravity.CENTER_HORIZONTAL;
myImg.setLayoutParams(lp);
UPDATE : Another way to do this : 更新:另一种方法:
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.weight = 1.0f;
params.gravity = Gravity.CENTER;
imageView.setLayoutParams(params);
I think , this one will work for you 我想,这个会对你有用
FrameLayout.LayoutParams layoutParams = new ScrollView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams1.gravity(YourGravity);
yourImage.setLayoutParams(layoutParams);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.