Centering a background image in Android

2019-03-09 19:55发布

问题:

I have a background image about 100 x 100 that I want to center in an Android app. Is there a way to do this?

I'm thinking it would greatly help with orientation changes for simple apps.

回答1:

You can use BitmapDrawable for the case. Create centered.xml in res/drawable folder:

<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/your_image"
    android:gravity="center"/>

Then you can use centered drawable as background.



回答2:

Question is old and answer has one big weakness - we have no possibility to change image size, it means it fully depends from drawable we have.

While using newest Android design libraries the root of activity view will be CoordinatorLayout or DrawerLayout and those layouts has no default view showing hierarchy, it means that first child view will be overshadowed by any next one, and second by third and ... to last one. So to have centered background We need to add as first child LinearLayout with centered image inside it. Some code snippet:

<android.support.v4.widget.DrawerLayout>
<!-- first child -->
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    >
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:src="@drawable/some_background"
        />
</LinearLayout> 
... next view will be above

We can fully customize size of image which will be centered by LinearLayout gravity option. Important is also to have match_parent on width and height of LinearLayout, thanks that center will be center of parent view also.

The same thing can be done in RelativeLayout or any other layout which enable child views overlapping.