Translate

Tuesday, 9 February 2016

Java Source Code

Let's see the java source file created by the Eclipse IDE:
File: MainActivity.java
  1. package com.example.helloandroid;  
  2. import android.os.Bundle;  
  3. import android.app.Activity;  
  4. import android.view.Menu;  
  5. import android.widget.TextView;  
  6. public class MainActivity extends Activity {//(1)  
  7.     @Override  
  8.     protected void onCreate(Bundle savedInstanceState) {//(2)  
  9.         super.onCreate(savedInstanceState);  
  10.                 
  11.         setContentView(R.layout.activity_main);//(3)  
  12.     }  
  13.     @Override  
  14.     public boolean onCreateOptionsMenu(Menu menu) {//(4)  
  15.         // Inflate the menu; this adds items to the action bar if it is present.  
  16.         getMenuInflater().inflate(R.menu.activity_main, menu);  
  17.         return true;  
  18.     }  
  19. }  
(1) Activity is a java class that creates and default window on the screen where we can place different components such as Button, EditText, TextView, Spinner etc. It is like the Frame of Java AWT.
It provides life cycle methods for activity such as onCreate, onStop, OnResume etc.
(2) The onCreate method is called when Activity class is first created.
(3) The setContentView(R.layout.activity_main) gives information about our layout resource. Here, our layout resources are defined in activity_main.xml file.
File: activity_main.xml
  1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     tools:context=".MainActivity" >  
  6.     <TextView  
  7.         android:layout_width="wrap_content"  
  8.         android:layout_height="wrap_content"  
  9.         android:layout_centerHorizontal="true"  
  10.         android:layout_centerVertical="true"  
  11.         android:text="@string/hello_world" />  
  12. </RelativeLayout>  
As you can see, a textview is created by the framework automatically. But the message for this string is defined in the strings.xml file. The @string/hello_world provides information about the textview message. The value of the attribute hello_world is defined in the strings.xml file.
File: strings.xml
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <string name="app_name">helloandroid</string>  
  4.     <string name="hello_world">Hello world!</string>  
  5.     <string name="menu_settings">Settings</string>  
  6. </resources>  
You can change the value of the hello_world attribute from this file.

No comments:

Post a Comment