I´m trying to create my first Android app, but I can´t do what I want. My idea is to create a simple score counter. I have an activity with a listview. Each item of the listview has a TextView with a name, two buttons for adding and subtracting, and a TextView for the score.
My idea was to show a custum numberpicker when the user clicks on the score, to select a number to increase a decrease. The custom numberpicker has an interface to use callback method to get the number selected.
In the activity class, I have a custom adapter for the listview, and a viewholder class to improve the functionality. I have several doubts/problems:
1) When can I define the listeners for the buttons/textviews? Currently I have the listeners in the viewholder, but i'm not sure if it is the better solution, maybe it's better to define them in the adapter, or even create an onitemclicklistener for the listview.
2) Can I implement the method defined in the numberpicker dialog interface inside the adapter or viewholder class? I have tried it but I get a cast exception because the inner class isn't an activity...
3) If I implement the interface method in the activity (outer) class, I´m not able to modify the desired textview that invoked the numberpicker...
My two main problems are where and how to define the listener for each view in the listview rows and how to get the number of the numberpicker dialog and continue with the execution...
Could anyone help me?
Thanks.
To use a listener in a view inside an adapter, the listener should be declared in the adapter and a new listener instance should be created for each view.
private static class ViewHolder {
private CustomListener listener;
private Button incrementBtn;
}
Now in the getView()
method:
holder.listener = new CustomListener(position);
holder.incrementBtn.setOnClickListener(holder.listener);
Now define an inherited class to implement the onClick()
method:
private class CustomListener implements View.OnClickListener {
private int position;
protected CustomListener(int position) {
this.position = position;
}
@Override
public void onClick(View v) {
//increment score here
notifyDataSetChanged();
}
}
Once the onClick()
method finishes, the view with update via notifyDataSetChanged()
with the new score.
To use the number picker dialog, it's the same pattern just with a DialogInterface.OnClickListener
defined in the viewholder.