Our final article in the Half Dozen Hello Worlds will introduce you to activities. What is an activity? It is a single screen that a user interacts with on their Android device. You’ve actually been using activities throughout these tutorials, we just haven’t examined them.
First, let’s create a new Android Project.
Here is the source code that is generated for us:
package com.learnandroid.helloworld;
import android.app.Activity;
import android.os.Bundle;
public class HelloWorld6Activity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
|
Since we are discussing Activities, you should notice that we are importing android.app.Activity. You should also note that our class is extending Activity. This gives us basic functionality to present our screen to the user without much work on our part. There are other classes we can use, that also inherit from Activity to provide us different functionality. In
this article we used a ListActivity to present a list to the user. In fact, let’s go ahead and make the changes described in that article to our code.
package com.learnandroid.helloworld;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
public class HelloWorld6Activity extends ListActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListAdapter adapter = createAdapter();
setListAdapter(adapter);
}
/**
* Creates and returns a list adapter for the current list activity
* @return
*/
protected ListAdapter createAdapter()
{
// Create some mock data
String[] testValues = new String[] {
"Hello 1",
"Hello 2"
};
// Create a simple array adapter (of type string) with the test values
ListAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, testValues);
return adapter;
}
}
|
You might have noticed that I named the items on my list “Hello 1″ and “Hello 2″. That’s because we are going to use Intents to call the programs we created in
Part 1 and
Part 2 of this series.
No comments:
Post a Comment