I have recently started making an Android app that requires a list of 20 names and counters for each individual name, both displayed on the screen. Every time someone taps a name, the counter for that name increases by one. This means that the name and the counter need to be ‘connected’ in some way.
I started off by creating a basic list of names using a ListView. This is my code:
public class ExampleActivity extends ListActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] NAMES = getResources().getStringArray(R.array.names_array);
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, NAMES));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 0) //Shows toast with name
Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
}
}
Here’s the list_item.xml file:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp" >
</TextView>
Now I’m looking for a way to display the counters in the list. The most user friendly one in my opinion would be a list in which the names are displayed on the left (which is currently the case) and their counters on the right (in one line with the names; alignment in a list is not my problem).
However, since I’m just a beginner in Android, I’m not sure how to pull this off. My first problem is that I don’t know how to somehow merge my list of 20 names with a list of 20 integers and make these integers specific for each name. My second issue is how to display all this on the screen.
Organize your row data(name + counter) in a simple
Modelclass:Then construct a row layout to show the name and counter:
Finally bind the
Modeldata to the row layout:To use your new adapter:
The
ListActivityalready has theOnItemClickListenerimplemented, is theonListItemClickmethod: