我有以下问题:我实现了一个HorizontalScrollView,其中包含一个LinearLayout和一个
ImageView.在这种情况下,图像大约是屏幕宽度的50%.所以我想让它居中.不幸的是,我发现中心的唯一方法是在LinearLayout上使用layout_gravity =“center”.
这是我的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.有人有一个想法,我怎么能达到这个或者知道一个不同的方式?我通过Google发现的所有事情都不像this post那样为我工作.
谢谢!
解决方法
做这样的事情
- LayoutParams lp = new LayoutParams();
- lp.gravity= Gravity.CENTER_HORIZONTAL;
- myImg.setLayoutParams(lp);
更新:
另一种做法:
- LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
- LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
- params.weight = 1.0f;
- params.gravity = Gravity.CENTER;
- imageView.setLayoutParams(params);