开发者

Centering a background image in Android

开发者 https://www.devze.com 2023-01-18 07:23 出处:网络
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 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.


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.


Or if you want to use your mipmap image, you should use item instead of bitmap:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/app_bg_color" />
    <item android:drawable="@mipmap/ic_launcher_round"
    android:gravity="center"/>
</layer-list>


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.


With a ConstraintLayout you can set the background tag directly. To be honest it took me a few hours to work this one out but it's a lot simpler than you might think ;)

0

精彩评论

暂无评论...
验证码 换一张
取 消