Connect Layout xml to Java code

Description

The code that connects the activity to the UI (main_layout_xml_file.xml) is the setContentView() method:

Example


/*from w w  w  .java  2s  .c o  m*/
package com.java2s.app;
import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

Add the following code in bold to the res/layout/ your main xml file for layout:


<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
  android:layout_height="fill_parent" 
  android:orientation="vertical" > 
//from  www .  java  2  s  .co  m
  <TextView 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:text="@string/hello" /> 
   
  <TextView 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:text="This is my first Android Application!" /> 

  <Button 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:text="And this is a clickable button!" /> 
   
</LinearLayout> 
Connect Layout xml to Java code

Note

R.layout.main refers to the main.xml file located in the res/layout folder.

As you add additional XML files to the res/layout folder, the filenames will automatically be generated in the R.java file.

The onCreate() method is one of many methods that are fired when an activity is loaded.





















Home »
  Android »
    Android UI »




UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView