Sunday, 19 July 2009

Exercise: Hello World with EditText input


In this exercise, I will implement a simply Hello World Andrid application; there is a EditText, after user enter name and click OK button, the Title of the application will be changed accordingly.

First of all, generate a Android Project in Eclipse, as described in the previous article, Install Android SDK on Eclipse 3.5 Galileo.

Modify the main.xml to change the UI screen.


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<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="Who you are?"
/>
<EditText
android:id = "@+id/message_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:id = "@+id/ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OK" />
<Button
android:id = "@+id/cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cancel" />
</LinearLayout>
main.xml

And then, change the HelloAndroid.java as follow:


package com.example.helloandroid;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class HelloAndroid extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);


Button okButton = (Button) findViewById(R.id.ok);
okButton.setOnClickListener(okOnClickListener);
Button cancelButton = (Button) findViewById(R.id.cancel);
cancelButton.setOnClickListener(cancelOnClickListener);
}
private Button.OnClickListener okOnClickListener =
new Button.OnClickListener(){
@Override
public void onClick(View v) {
EditText edit_text = (EditText)
findViewById(R.id.message_text);
CharSequence edit_text_value =
edit_text.getText();
setTitle("Hello:"+edit_text_value);
}
};

private Button.OnClickListener cancelOnClickListener =
new
Button.OnClickListener(){
@Override
public void onClick(View v) {
finish();
}
};
}
HelloAndroid.java

No comments:

Post a Comment