如何与我的适配器类中的片段进行通信

Vin*_*rdo 4 java android android-fragments

我已经创建了一个自定义适配器类.在那个类中,我有一个代码,当我点击我的listview布局时,必须向我的片段发送一条消息.谷歌搜索后,最好的方法可能是使用界面.其中大多数是活动与片段之间进行通信的示例.但就我而言,我对如何在我的适配器类与片段类之间进行通信没有任何想法.我说我在我的适配器类中创建一个接口,如:

public interface SuccessResponse{
    void onSuccess();
}
Run Code Online (Sandbox Code Playgroud)

在我的适配器类中的LinearLayout上,我希望它是这样的:

linearLayout.setOnClickListener(new View.OnClickListener{
    @Override
    public void onClick (View view){
        SuccessResponse.onSuccess();
    }
})
Run Code Online (Sandbox Code Playgroud)

然后我想确保我的片段页面获取onSuccess()方法并执行以下操作:

public class MyFragment extends ListFragment implements Adapter.SuccessResponse{
    @Override
    public void onSuccess(){
        //do Something
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法做上面这样的事情?

sad*_*dat 10

以下代码可以帮助您.

public class ExampleFragment extends Fragment implements MyAdapter.SuccessResponse{

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View contentView  = inflater.inflate(R.layout.my_layout, container, false);
        MyAdapter myAdapter = new MyAdapter(getActivity(), 0);
        myAdapter.successResponse = this;
        return contentView;
    }

    @Override
    public void onSuccess() {

    }
}
Run Code Online (Sandbox Code Playgroud)

class MyAdapter extends ArrayAdapter{
    SuccessResponse successResponse;

    public MyAdapter(Context context, int resource) {
        super(context, resource);
    }

    public interface SuccessResponse{
        void onSuccess();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        //ur views
        linearLayout.setOnClickListener(new View.OnClickListener{
            @Override
            public void onClick (View view){
                if(successResponse!=null)
                    successResponse.onSuccess();
            }
        })
    }
}
Run Code Online (Sandbox Code Playgroud)