Sunday, September 22, 2013

Difference Between Margin and Padding attributes

Let's start with example.

activity_practice.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
android:orientation="vertical"
android:background="#d0d0d0"
    tools:context=".PracticeActivity" >

<Button 
   android:id="@+id/btn1"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="@string/btn1"
   />


</LinearLayout>

PracticeActivity.java

package com.agilissystems.practicework;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class PracticeActivity extends Activity implements OnClickListener {

private Button oBtn1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_practice);
        
        oBtn1 = (Button) findViewById(R.id.btn1);

        oBtn1.setOnClickListener(this);

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.practice, menu);
        return true;
    }


@Override
public void onClick(View v) {
// TODO Auto-generated method stub

switch (v.getId())
{
case R.id.btn1:
Toast.makeText(this, "You clicked on Button 1 !!!", Toast.LENGTH_LONG).show();
break;


}
}
    

}

Strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Practicework</string>
    <string name="action_settings">Settings</string>
<string name="btn1">Button 1</string>

</resources>

When you run the above application will place the button element at left top corner of the screen. Margin attribute allows spacing surrounding the element. Add below line to button element of activity_practice.xml file.

android:layout_margin="20dp"

will add 20dp spacing surrounding the button element. but if you want to apply the spacing to specific side(s) then there are attributes called layout_margintop, layout_marginbottom, layout_marginleft and layout_marginright.

Now, we need to apply spacing surrounding the text of the button then there is attribute called "padding", add below line to button element.

android:padding="40dp"

It will add 40dp spacing to all side of text inside the button. there are other attributes like paddingLeft, paddingRight, paddingTop, paddingBottom, paddingStart, paddingEnd which will add spacing to specif side of the text.

Hope, now you are clear about the difference between margin and padding attributes.




 

No comments:

Post a Comment