问题描述
我有以下问题:我实现了一个 HorizontalScrollView
包含在一个案件一个的LinearLayout
和的ImageView
。在这种情况下,图像是大约50%的屏幕宽度。所以我想居中。不幸的是,只有这样,我发现居中是,使用 layout_gravity =中心
在的LinearLayout
。
I've got the following problem: I implemented a HorizontalScrollView
which contains in one case a LinearLayout
and an ImageView
. In this case the image is about 50% of the screen width. So I want to center it. Unfortunately the only way I found to center it is, to use layout_gravity="center"
on the LinearLayout
.
下面是我的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>
不过,我需要设置 layout_gravity
编程。是否有人有一个想法我如何能做到这一点,或知道不同的方式?所有我通过谷歌找到的东西都没有工作对我来说就像这篇文章。
But I need to set the layout_gravity
programmatically. 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.
谢谢!
推荐答案
做这样出头的:
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);
这篇关于Android的 - 编程设置Layout_Gravity了的LinearLayout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!