Open main menu

CDOT Wiki β

Changes

MAP524/DPS924 Lecture 5

2,313 bytes added, 21:56, 17 July 2015
Created page with '= Adapters = We'll finish the '''Spinner''' example from last week's lecture. Unlike the other Views we looked at last week it requires the use of an Adapter. See the [http://de…'
= Adapters =

We'll finish the '''Spinner''' example from last week's lecture. Unlike the other Views we looked at last week it requires the use of an Adapter. See the [http://developer.android.com/guide/topics/ui/controls/spinner.html official documentation here]. Note that in the setup you have:

* A store of data (an array of values)
* A UI element to display those values (the spinner)
* An adapter to connect the first two (specifically here an ArrayAdapter)

= ListView =

This should be as simple as a spinner, it appears to do essentially the same thing, but it's more complicated to build. Follow these steps:

* Create a new Android app and name it My List.
* Add a ListView below the TextView in your activity_main.xml file.
* Create a second layout file named "activity_listview.xml" with root element set to TextView (no layout element). It should look like this
<pre><!?xml version="1.0" encoding="utf-8"?>

<textview xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"/></pre>

* Create a new [https://scs.senecac.on.ca/~andrew.smith/android/2015-02/arrays.xml arrays.xml] file inside your values directory.
* Add a String array named colourNames as a class variable in MainActivity like this:
<pre>String[] colourNames;</pre>
* Tie your array to your xml array like this :
<pre>colourNames = getResources().getStringArray(R.array.listArray);</pre>
* Create a ListView object pointing to your list view like this:
<pre>ListView lv = (ListView) findViewById(R.id.listView);</pre>
* Create an array adapter and attach it to your list view like this:
<pre>ArrayAdapter aa = new ArrayAdapter(this, R.layout.activity_listview, colourNames);
lv.setAdapter(aa);</pre>
* You can now run your app to see your scrollable list of colours.
* Now add an onClickListener to your listview like this:

<pre>lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});</pre>
* Run your app again and this time select a colour by clicking it.
* You should see a Toast with the selected colour name pop up.