I have a layout with a TextView
and I want the android:gravity
attribute value to be pulled from another resource file, android:gravity="@???/item_align"
, where item_align
is the name of a resource in another xml file. The typical values used in a layout, center
or bottom
or bottom|center_horizontal
don't work. What type goes in the @???
, integer works, if I replace the strings with the actual integer value ("center" replaced with 0x011). But, that's not a good solution.
So, the question(s): How do I refer to the value in the layout file, and what does the item look like in the resource file?
<TextView
android:id="@+id/item_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_margin="1dp"
android:layout_centerHorizontal="true"
android:gravity="@???/item_align"
android:text="65"
android:textSize="20sp"
android:typeface="sans"
android:textStyle="bold"
android:textColor="#000000" />
Layout Binding expressions Expressions in the XML layout files are assigned to a value of the attribute properties using the “ @{} " syntax. We just need to use the basic syntax @{} in an assignment expression.
Resource ID. A unique resource name for the element, which you can use to obtain a reference to the ViewGroup from your application. See more about the value for android:id below. android:layout_height.
So in general android:layout_gravity attribute is used by child views to tell their parent how they want to be placed inside it, while android:gravity is used by the parent layout to tell the child views how they should be placed inside it.
Gravity and layout_gravity both are the XML attributes. The android:gravity attribute is used to arrange the position of the content inside a view (for example text inside a Button widget). The android:layout_gravity is used to arrange the position of the entire View relative to it's container.
In order not to break the standard constants and avoid highlighting in red in Android Studio, you can create two styles (in styles.xml) in the /values and /values-sw600dp folder
/values/styles.xml
<style name = "AppContainerLayout">
<item name = "android:gravity">top|start</item>
</style>
/values-sw600dp/styles.xml
<style name = "AppContainerLayout">
<item name = "android:gravity">center</item>
</style>
And just use in layout
<LinearLayout
style = "@ style/AppContainerLayout"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:orientation = "vertical">
// childs
</LinearLayout>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With