Callback from Adapter

北战南征 提交于 2019-11-28 12:26:48

You need to tell the adapter which implementation of the OnShareClickedListener() to use. Right now in your adapter the field mCallback is never assigned to, either you need to have a setOnSharedClickedListener() method in your adapter which you then call from your mainActivity and set it with the main activity's implementation or you need to take in the constructor.

My suggestion would be to use a setter instead of constructor. So what you need to do is this.

Your ListAdapter

public class ListAdapter extends BaseAdapter implements View.OnClickListener {

    OnShareClickedListener mCallback;
    Context context;
    public static List<String> url_list;

    public ListAdapter(Context c, List<String> list) {
        this.context = c;
        url_list = list;
    }

    public void setOnShareClickedListener(OnShareClickedListener mCallback) {
        this.mCallback = mCallback;
    }

    public interface OnShareClickedListener {
        public void ShareClicked(String url);
    }


    @Override
    public void onClick(View v) {
        mCallback.ShareClicked("Share this text.");
    }
}

Your MainActivty

public class MainActivity extends ActionBarActivity implements ListAdapter.OnShareClickedListener{

    ListView main_list;
    List<String> url_list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        main_list = (ListView) findViewById(R.id.listView);
        ListAdapter nListAdapter = new ListAdapter(this, url_list);
        nListAdapter.setOnShareClickedListener(this);
        main_list.setAdapter(nListAdapter);
    }

    @Override
    public void ShareClicked(String url) {
        Log.e("Test", url);
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!