Reputation: 177
I have multiple horizontal linear layouts. Whithin each of these layouts which are listed vertically, I have a TextView followed by an EditText. I want to give a constant left margin to all the EditText views only so that they get aligned, how can I accomplish that? Here is the partial code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="5dp"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:paddingTop="5dp" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/pNameL"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="Segoe ui"
android:text="Name"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="@+id/editText2"
style="@style/editText_style"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10" >
</EditText>
</LinearLayout>
Upvotes: 1
Views: 2177
Reputation: 8320
Create a style in res/values/style.xml file. If style.xml is not present then create a new one.
<style name="editText_style">
<item name="android:layout_marginLeft">30dp</item>
<item name="android:layout_marginRight">30dp</item>
</style>
Then in your layout files (in which you want to change margin) under <EditText>
tag, apply this style using :
style="@style/editText_style"
EDIT : In case, where your parent is horizontal oriented, you cannot apply margin relative to your parent.
Try using layout:weight
property. For example, if you want that your EditText starts at half of its parent and you have total 2 view in your parent including EditText then set layout:weight
of both views to, let's say, 0.5. This gives both of the views equalspace in their parent.
This will work only if all the LinearLayouts
, where you want to make change, contains equal no. of views. If for different LinearLayout
contains different no. of views then you cannot use style or there is no way to make change from single place.
Note : Using layout:weight
property you cannot obtain static margin value. It is dependent on your parent size and it may vary on different screen sizes.
Upvotes: 2