Call an Activity method from inside adapter?

2020-07-27 19:06发布

I have a custom Adapter that has a click Listener on the ListView image.

This code is inside the Adapter GetView:

holder.iconImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

          //code to do stuff when the image is clicked
}

My images in the listview consist of images of folders (to represent a folder) and actual images.

So if the user clicks on a folder image, I want to be able to call a method called "moveDownFolder" in ActivityA.

I'm not sure if this can be done inside of the Adapter?

[EDIT] Basically in ActivityA I have a Click Listener on the custom ListView, so if they click on the text in the custom ListView, it moves down a folder (if it is a folder).

But they can click on an image in the ListView, it opens the image in a new activity. BUT if they click on the folder icon in the listview (which is an image of course in the ImageView) - I want the code to move down a folder, instead of trying to open the image.

标签: android
3条回答
欢心
2楼-- · 2020-07-27 19:42

Yes it can be done , just make your function as follows static public moveDownFolder() . You need to be sure that activity is created. to call that function from Adapter just simply do : YourActivity.moveDownFolder()

查看更多
够拽才男人
3楼-- · 2020-07-27 19:43

I Recommending on using interface as listener.

For example:

1, create your interface:

public interface MyListener {

void folderClicked();
}

2, Let your ActivityA to implement this Interface like this:

public class ActivityA extends Activity implements MyListener 

3, you will have to auto overide the method folderClicked it will look like this:

@Override
protected void folderClicked() {
  // Do your stuff here.

}

4, send the activity listener to the adapter with constructor like this:

MyAdpater adapter = new MyAdpater(ActivityA.this);

5, in your adapter class your code should be like this :

public class TimeLineAdapter extends BaseAdapter {

private MyListener mListener;


public TimeLineAdapter(MyListener listener) {
    super();

    mListener = listener;


}

holder.iconImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
         mListener.onFolderClicked()
      //code to do stuff when the image is clicked
 }
查看更多
叛逆
4楼-- · 2020-07-27 19:44

If the adapter is an inner class of ActivityA, try:

ActivityA.this.moveDownFolder();
查看更多
登录 后发表回答