Centering a background image in Android

假装没事ソ 提交于 2019-12-31 08:57:29

问题


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.




回答3:


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 ;)



来源:https://stackoverflow.com/questions/3847979/centering-a-background-image-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!