Home > database >  How to get Fragment class name in adapter
How to get Fragment class name in adapter

Time:09-05

I am working on a Android app since I am new I can't find a way to get the fragment class name ReadFragment into the Adapter onBindViewHolder method.Any hint how can I get the class name or index of the fragment since I am using 2 fragments and want to display diferent data in each.

Fragment:

public class ReadFragment extends Fragment {

View view;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,


    return view;


}

Adapter

@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {}

CodePudding user response:

  1. Adapter Side
// ..
private Class fragmentCls;

public MyRecyclerViewAdapter(..., Class fragmentCls) {
    // ..
    this.fragmentCls = fragmentCls;
}
// ..
  1. Fragment Side
// ..
adapter = new MyRecyclerViewAdapter(.., MyFragment.class);
// ..
// recyclerView.setAdapter(adapter);
// ..

So then you can use the fragmentCls field to get to know which is the caller fragment..

CodePudding user response:

You can check if the fragment in the container is instanceof any Fragment

Fragment fragment = context.getFragmentManager().findFragmentById(R.id.fragment_container);
if(fragment instanceof FirstFragmentClass){
   //do something
} else if(fragment instanceif SecondFragmentClass){
   //do something
}
  • Related