Wednesday, February 15, 2012

Android: navigation between screens

Each screen called "Activity"

create a new class that extends from "Activity"
create a new Android XML file to set up the layout

make sure that this new Activity is included in the AndroidManifest.xml.
in eclipse, open the AndroidManifest.xml > Application tab > Application nodes > Add... > Create a new element at top level > Activity.
Name: Browse > select new Activity class created

easier way is to edit the xml manually and add
<activity android:name="{name of new Activity subclass}"></activity>
in the <application> tag.

using Singleton design pattern, data can be passed to next screen.

For example:


public class Apple {
public static int number = 1;
double price = 0.5;
int size = 2;
String color = "red";
public static String name = "Apple";
public static Apple instance;
public void grow()
{
size++;
}
public String getColor()
{
return color;
}
}

in main Activity subclass:

Apple a = new Apple();
Apple.instance = a;

Apple.number++;
// et is editable text UI
Apple.name = et.getText().toString();
a.grow();


// go to next screen
Intent intent = new Intent(this, NextActivity.class);
startActivity(intent);

next Activity subclass:


public class NextActivity extends Activity implements View.OnClickListener{
Button b;
TextView tv;
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.next);
        tv = (TextView)this.findViewById(R.id.textView1);
        b = (Button) this.findViewById(R.id.button1);
        tv.setText("Hello, " + Apple.name + ", size: " + Apple.instance.size+ ". number of apple: " + Apple.number);
        b.setOnClickListener(this);
}


public void onClick(View v) {
// TODO Auto-generated method stub
// end this activity to go back to prev screen
this.finish();
}
}



No comments: