2

I've been trying to center a logo (an ImageView) in the ToolBar. I finally did it but the main reason it took so long, I couldn't find layout_gravity property in auto-complete or in Android Studio's Design pane> Properties table. Only gravity related property is foregroundGravity.

Now, I think ImageView is an ImageView. It must have layout_gravity where ever it is but not being able to find the property made me think it is not available when you use android.support.v7.widget.Toolbar.. Has anyone had a similar experience or do you know why it happens?

Below is my code and the min API level is 10.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/ColorPrimary"
    android:theme="@style/ThemeOverlay.AppCompat.Dark"
    android:layout_gravity="top"
    >
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@mipmap/comp_logo"
            android:layout_gravity="center_vertical|center_horizontal"
            />

</android.support.v7.widget.Toolbar>
melis
  • 1,145
  • 2
  • 13
  • 30

1 Answers1

3

The layout_ prefix on an attribute indicates that attribute is a property of the parent View's LayoutParams.

In the layout you posted for example, the layout_gravity on your ImageView is used to tell the Toolbar where to position the image. The ImageView itself does nothing with that attribute.

Note that many Views (such as TextView) do support a gravity attribute, which is how that View will layout its own content. layout_gravity will position the View as a whole within its parent, whereas gravity positions the View's content within that View. See also: Gravity and layout_gravity on Android.

The reason Android Studio isn't offering layout_gravity as an option on your Toolbar is that in this layout your Toolbar has no parent, and thus Android Studio has no idea what layout attributes are available to it. This makes sense, as your layouts should be completely independent of any parent that you may put them in.

Community
  • 1
  • 1
Bryan Herbst
  • 66,602
  • 10
  • 133
  • 120
  • Thanks @Tanis.7x! I think I am about to understand. But...If Android Studio doesn't know which properties available to the View why does it offer the layout_margin properties? My guess is, layout_margin properties are available to every View by default. Am I correct? Where should I look to find out? – melis Aug 25 '15 at 15:51
  • I can't speak to why it offers `layout_margin`- it is only available when the parent ViewGroup's LayoutParams extend [`MarginLayoutParams`](http://developer.android.com/reference/android/view/ViewGroup.MarginLayoutParams.html), but you are correct that that it is fairly common. – Bryan Herbst Aug 25 '15 at 16:01