All user interface elements in an Android app are built using View and ViewGroup objects.
View
An object that draws something on the screen that the user can interact with.
ViewGroup
An object that holds other View(and ViewGroup)
- You can use two ways to creating Views
- Dynamically Add By Coding
LinearLayout ll = new LinearLayout(getApplicationContext());
- Statically Define in XMLs
<android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:orientation=”vertical” >
If you define it in XML you should call setContentView() method to load that XML in Activity.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
}
- Every View and View Group object supports their own variety of XML attributes. Some attributes are specific to a View object (for example, Text View supports the text Size attribute)
- Some are common to all View objects, Like id , layout parameters and etc.
ID Attribute
- Any View object may have an integer ID associated with it, to uniquely identify the View within the tree.
android:id=”@+id/my_button”
Define & Retrieve
Define in XML
<android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”@string/btn_login_text”/>
Retrieve By Activity
Button btnLogin= (Button) findViewById(R.id.btn_login);
Layout Parameters
- XML layout attributes named layout_something define layout parameters for the View that are appropriate for the View Group in which it reside
Eg:
- layout_widthand layout_height
- wrap_contenttells your view to size itself to the dimensions required by its content
- fill_parent(renamed match_parentin API Level 8) tells your view to become as big as its parent view group will allow.
Layout Positioning
- The geometry of a view is that of a rectangle.
- A view has a location, expressed as a pair of left and top coordinates, and two dimensions, expressed as a width and a height.
Paddings
- setPadding(int left, int top, int right, int bottom)
Related XML Attributes
android:padding
android:paddingBottom
android:paddingLeft
android:paddingRight
android:paddingTop
Margins
- setMargins(int left, int top, int right, int bottom)
- Related XML Attributes
android:layout_marginLeft
android:layout_marginTop
android:layout_marginRight
android:layout_marginBottom