Android View with CustomEvent, passing View as Argument

711 views Asked by At

I have a DataAdapter class whose getView() returns a Custom View Class. The View itself is a LinearLayout that contains a few controls, one of which being a CheckBox. It also has a few properties - an ID from the database and it's index in the DataAdapter.

When the CheckBox OnCheckedChange event fires, I want an event to fire in the DataAdapter to so I know to change the underlying data. I can set up a custom Event in the view using an interface:

private OnChangedListener mListener;

public interface OnChangedListener{
    public void onChanged();
}

public void setOnChangedListener(OnChangedListener eventListener) {
    mListener=eventListener;
}

and call that from the CheckedChange of the CheckBox:

private OnCheckedChangeListener checkChanged = new OnCheckedChangeListener(){
    @Override
    public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
        mListener.onChanged();
    }
}; 

but what I can't do is work out a way to pass back the view as an argument. If I change the interface to return the View:

public interface OnChangedListener{
    public void onChanged(MyCustomView arg0);
}

I can't return the view from inside the OnCheckedChangeListener():

private OnCheckedChangeListener checkChanged = new OnCheckedChangeListener(){
    @Override
    public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
        mListener.onChanged(this);
    }
}; 

I get an error: "The method onChanged(MyCustomView) in the type MyCustomView.OnChangedListener is not applicable for the arguments (new CompoundButton.OnCheckedChangeListener(){})"

I thought about using a Handler.Post, but then I'd be inside a Runnable so I still can't expose the View.

I'm sure there must be something simple I'm missing...

2

There are 2 answers

0
steverus_snape On BEST ANSWER

The answer was simple. The CheckButtons parent should be the instance of the view I'm looking for:

    public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
        ViewParent parent = arg0.getParent();

        if (parent instanceof CustomView){
            Custom myView = (CustomView) parent;
            mListener.onChanged(myView);
        }
    }
2
Mohamed_AbdAllah On

this in mListener.onChanged(this); does not refer to your View, it refers to the OnCheckedChangeListener (the wrapping class). You need to return the View like this:

mListener.onChanged(/*reference to your view*/)