Tuesday, February 14, 2012

Android: Hello World, XML, Java

Follow instructions to install Android SDK, Eclipse, ADT plugin
Set up AVD
Start new Android project

in res\layout\main.xml
open it to set up layout.
set id. strange why android makes programmer to add "@+id/" before the id. more memory load for the programmers.

main.xml

<?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" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Hello World" android:id="@+id/hello_txt"/>

    <EditText
        android:id="@+id/editText1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="123">

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="146dp"
        android:layout_height="wrap_content"
        android:text="Press me!" />

</LinearLayout>

HelloActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.view.*;
import android.widget.*;

public class HelloActivity extends Activity implements View.OnClickListener{
TextView tv;
Button b;
EditText et;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tv = (TextView)this.findViewById(R.id.hello_txt);
        b = (Button) this.findViewById(R.id.button1);
        et = (EditText) this.findViewById(R.id.editText1);
        b.setOnClickListener(this);
    }
    // implement interface View.OnClickListener method
public void onClick(View v) {
// TODO Auto-generated method stub
tv.setText("Hello, " + et.getText());
}
}



No comments: