Android: first interactive app
April 01, 2011 15:46:16 Last update: April 01, 2011 15:47:57
Follow these steps to build your first app that allows you to enter input and click a button:
- Start from the Hello World example.
- Edit
res/layout/main.xml, change the contents to:<?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/question" /> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/name" /> <Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="@string/sayhi" android:onClick="sayHi" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/hello" /> </LinearLayout>
This adds a text input field and a button to the screen. It also declaratively binds an event handler (onClick="sayHi") to the button.
- Add the string resources (
res/values/strings.xml):<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">HelloWorld</string> <string name="greeting">Greeting</string> <string name="question">What\'s your name?</string> <string name="sayhi">Say Hi</string> </resources>
- Implement the event handler (
src/com/android/helloworld/HelloWorld.java):package com.android.helloworld; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.TextView; public class HelloWorld extends Activity { private static final String LOG_TAG = "HelloWorld"; private EditText nameField; private TextView greeting; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); nameField = (EditText) findViewById(R.id.name); greeting = (TextView) findViewById(R.id.hello); } public void sayHi(View view) { CharSequence name = nameField.getText(); greeting.setText("Hello " + name + "!"); } }
- Change the Activity label to Greeting (
AndroidManifest.xml):<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.android.helloworld" android:versionCode="1" android:versionName="1.0"> <application android:label="@string/app_name" android:icon="@drawable/icon"> <activity android:name="HelloWorld" android:label="@string/greeting"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
- Reinstall the debug package to the emulator:
ant install
- The screen should look like this: