Issue
I have created a custom adapter class. In that class, I have a code that will have to send a message to my fragment, when I clicked on my listview layout. After googling, the best approach to do it may be using interface. Most of them are the example of communicating between activity with the fragment. But in my case, I don't have any ideas about how to communicate between my adapter class with my fragment class. let says I create an interface in my adapter class like:
public interface SuccessResponse{
void onSuccess();
}
and on the LinearLayout inside my adapter class I want it to be something like:
linearLayout.setOnClickListener(new View.OnClickListener{
@Override
public void onClick (View view){
SuccessResponse.onSuccess();
}
})
Then I want to make sure my fragment page get the onSuccess() method and do something like :
public class MyFragment extends ListFragment implements Adapter.SuccessResponse{
@Override
public void onSuccess(){
//do Something
}
}
Is there any way to do something like above?
Solution
Update If you are looking for a solution in Kotlin
class ExampleFragment : Fragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val adapter = MyAdapter(){
Log.d("zzzz", "$it ")
}
}
}
class MyAdapter (val onClick : (value: String) -> Unit): RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
holder.itemView.setOnClickListener {
onClick("something")
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
TODO("Not yet implemented")
}
override fun getItemCount(): Int {
TODO("Not yet implemented")
}
}
JAVA The following code may help you.
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() {
}
}
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();
}
})
}
}
Answered By - sadat
Answer Checked By - Mildred Charles (JavaFixing Admin)