Gravity了的LinearLayout

Gravity了的LinearLayout

本文介绍了Android的 - 编程设置Layout_Gravity了的LinearLayout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题:我实现了一个 Horizo​​ntalScrollView 包含在一个案件一个的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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 00:49