Android List Making!
November 27th, 2012!
Background
We have successfully created our first android app in the previous lab! But, what now? Well, we managed to send a message to a different screen. BUT, what if we want it in the same screen? Well, this is what we'll do today
Things that you already have
- Android SDK
- Eclipse Plug-in
- Your first app!
- A general idea of how things work
- SOME confusion, or TONS, but that's aight for now
Things we'll need
- A ListView object in our Main_Activity.xml
- An EditText
- A Button
- An ArrayList<String>
- An ArrayAdapter<String> (Android stuff we've never seen)
Preliminary Layout Steps
- Create a new project, lets call it List
- Modify main_activity.xml and remove the default hello world text. Make orientation vertical
- Add an EditText tag (this will make a text field), lets id this "myEditText", and give it a HINT string (I will call mine textbox). layout_width=match_parent, layout_height=wrap_content
- Add a Button tag (this will make a button for us). ID it button1 and TEXTstring (I call mine addbutton).l_w=match_parent, l_h = wrap_content
- Add a ListView ID it myListView. l_w = fill_parent, l_h = wrap_content.
Working Steps
- Lets add an "android:onClick" parameter to our button. The value we give this will ALSO BE THE NAME OF THE METHOD TO IMPLEMENT IN MainActivity
- Lets connect it all. So, we will need private references for EditText, ArrayList, ArrayAdapter, ListView
Modifying the onCreate method
- We need the first 2 lines, they're important!
- lets get references to ListView and editText by using (CAST) findViewById(R.id.NAME); NAME is what we determined the ID of the elements to be
- We need a new ArrayList of strings
- This part is the magic, we need to make a
new ArrayAdapter(this, android.R.layout.simple_list_item_1, NAME_OF_OUR_ARRAY_LIST - make our view set the adapter to be OUR array adapter
Last STEP
If you noticed, the app does nothing right? Well, we forgot to implement our special method when someone clicks the button. Lets go do that.
- add the String item from the editText field to the list
- notify the array adapter that data changed, by using the notifyDataSetChanged() method
- set the text to "" again
Things not to forget
- DON'T PANIC. We are both new at this, this is also my first (well second technically) time doing this kind of stuff.
- Add your STRINGS to your strings.xml file. Or else the compiler will complain.
Submissions
You do not have to submit this lab. This is only for your own benefit. You can chose not to do it, or come to lab; but be reminded that you do have a project that's based on android stuff so this might be helpful.