user3576118 user3576118 - 7 months ago 28
Android Question

How to make connections between listview and the activity that calls it

I am currently trying to make a shopping list activity. My activity consisted of a listview and a textview (showing the total price of all items).

For the item names, quantity, and subtotal prices will be inside the listview, and the user can change the number of quantity which I want to change the subtotal and the total price as well.

I have succeeded in changing the subtotal price in the listview, but the problem is how to change the total price that is "outside" of the listview.

I do the logic for changing the subtotal price inside the listview adapter class, is there any way that I can detect the change of a listview item from outside of the adapter class?


A solution could be to pass the instance of Total TextView through the constructor of the adapter.

Adapter myAdapter = new (context, txtTotal, ...);

Then, in the getView method of the adapter, when you write the quantity, currently you are changing the subtotal textview. with the total textview instance firstly get the value in a double, add or subtract the change. finally put result in the total textview.

Another solution could be to use LocalBroadcastManager when you change the subtotal TextView you could send an action(From the adapter class). example:

Intent intent = new Intent("change-total-event");
 intent.putExtra("xxxx", "20.50");//add data if you need

Then, in your Activity you need to register the broadcastreceiver, please follow the tutorial if you want to do this option. Finally, change the value of the textview in your broadcastreceiver.

// handler for received Intents for the "change-total-event" event 
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
  public void onReceive(Context context, Intent intent) {
    // Extract data included in the Intent
    String value = intent.getStringExtra("xxxx");
    //change the total textview