centerHorizontal does not centre the image correctly
Here is the XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/bg"
>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="4"
android:orientation="vertical"
>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_horizontal" //CENTER 01
>
<!--center button-->
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/img"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" //CENTER 02
/>开发者_StackOverflow;
//...
</RelativeLayout>
</LinearLayout>
<include android:id="@+id/banner" layout="@layout/banner"
android:layout_weight="1"
android:layout_gravity="bottom"/>
</LinearLayout>
The center button is centered, but not in the real center of the screen, but rather approx 50px to the right of the center. If I remove centerHorizontal
CENTER01, then this does not happen.
Does anyone know why is this happening?
Please try for //CENTER 02
:
android:layout_centerInParent="true"
This issue may be due to using of both Relative Layout and Linear Layout inside a xml file.
Change all Linear Layout to Relative Layouts so that Image View will be centered as you expected.
I too mingled both Linear Layout and Relative Layout in single XML and faces this kind of issue. Once i replaces all Linear Layout to Relative Layout my problem Resolved.
Try it.Thanks.Venky
Its because in Relative Layout center_horizontal isn't the command. that works for views wrapped in linear Layout. for RelativeLayout you need to use
android:layout_centerInParent="true";
as the center gravity command in linear
or
android:layout_centerHorizontal="true"
as the gravity center_horizontal in linear.
When you set android:gravity="center_horizontal"
on a parent, it influences the behaviour of its children. Hence, your ImageView
gets effected, creating the effect you see after already being placed in the center by other properties.
You can see this effect for yourself by placing a TextView
in there with android:layout_width="fill_parent"
.
精彩评论