简体   繁体   中英

method call from adapter class to activity

Adapter:

check_list_item.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        JPrequirements.prepareSelection(v, getAdapterPosition());
    }
});

JPrequirements is the activity. and prepareSelection is non-static method inside activity. I cannot access it from adapter.

ERROR:

non static method cannot be referenced from a static context

Which is right. that's why I tried with:

JPrequirements().prepareSelection(v, getAdapterPosition()); // Creating an instance...

But, the problem is I lost all activity component here. eg. layout components and other supporting variables. I don't want that. What is the best way to deal with this? How can I get updated value from adapter to activity? So, I can display it real-time.

Thanks.

You can achieve this via interface . Firstly, define an interface class as:

public interface ActivityAdapterInterface {
    public void prepareSelection(View v, int position);
}

Now, implement the interface in your Activity as:

public class JPrequirements extends AppCompatActivity implements ActivityAdapterInterface {
    ...
    public void prepareSelection(View v, int position) {
        // cool stuff here
    }
    ...
}

Make sure you pass this interface reference to your Adapter via its constructor. Then finally call it on click as:

check_list_item.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) {
        mActivityAdapterInterface.prepareSelection(v, getAdapterPosition());
    } 
}); 

[EDIT]

To provide the interface to your Adapter provide it the constructor.

public class YourAdapter ... {

    private ActivityAdapterInterface mActivityAdapterInterface;

    public YourAdapter(..., ActivityAdapterInterface activityAdapterInterface) {
        activityAdapterInterface = mActivityAdapterInterface;
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM