Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android adapter data changed to notify host activity

This is a my use case. I have an activity with a listview and a textview. The textview is the sum of all numbers on the listview, the listview has all the numbers.I have a custom adapter for this case.

On each row of the listview, I have a button. This button will change the number on this row. what I want to do is this:

  1. when user clicks the button, the value on each row is changed - doable.
  2. the sum on the textview also changes accordingly.

This is a simplified example. In reality, I also have a constraint that I have a data model to represent the data on each role. I am not able to extend the data model to DataSetObserver.

any help?

like image 371
Liangjun Avatar asked Jan 24 '26 03:01

Liangjun


1 Answers

You should create a listener, which listens for touch on your increment button and inside it call a method of the class extending an interface you created. To make it easy, in your adapter you will have:

public interface OnIncrementListener{
    onNumberIncremented();
}

private OnIncrementListener mListener;

//This is inside getView method of your adapter
myButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mListener.onNumberIncremented();
        }
});

Then your activity

public class MyActivity extends Activity implements OnIncrementListener {

   //inside onCreate
   myAdapter.setOnIncrementListener(this);
   //end onCreate

    @Override
    public void onNumberIncremented() {
         //Change value of your TextView here
    }
}
like image 124
MineConsulting SRL Avatar answered Jan 25 '26 17:01

MineConsulting SRL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!