Center ImageView inside another ImageView in Android

Deadly 提交于 2020-01-01 06:39:28

问题


Well I have to fit one ImageView inside another one. It is smaller and has to be exactly at the center. I have both images scaled for different screen resolutions but I can test only on one phone and I am wondering if I set the second image's height and width with dpi to fit my screen resolution will it be perfectly matched on all screens or is there any property in Android aside from setting the height and width that will automatically center one ImageView inside of other ImageView?

Edit: It's in RelativeLayout and the ImageViews are at the top left so I haven't added anything specific to the because they by default are there.

Edit2: Well changing the first ImageView to be RelativeLayout helps center the second image inside of it but then the RelativeLayout grows too big and enlarges the image that is background. Is there a way to make the RelativeLayout be as big as its background?


回答1:


try this

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

  <RelativeLayout
   android:layout_width="250dp"
   android:layout_height="250dp"  >

   <ImageView 
       android:id="@+id/base"
       android:layout_height="250dp"
       android:layout_width="250dp"
       android:src="@drawable/home"
       android:layout_alignParentLeft="true"
       android:layout_alignParentTop="true" />

    <ImageView 
       android:id="@+id/center"
       android:layout_height="150dp"
       android:layout_width="150dp"   
       android:src="@drawable/home"
       android:layout_centerInParent="true"
      android:layout_centerVertical="true"   />
 </RelativeLayout>

</RelativeLayout>



回答2:


You cannot put an imageView inside another. Hope the following code will be helpful for you.

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/background_image"
        android:gravity="center" >

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/image_on_center" />

    </LinearLayout>



回答3:


Use RelativeLayout and then use android:layout_centerInParent="true" remember the order you add the ImageViews will decide what is on top :)




回答4:


Try this:

android:layout_gravity="center"


来源:https://stackoverflow.com/questions/19020871/center-imageview-inside-another-imageview-in-android

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