I have an application (Java) which originally had 5 sections. All of these are fragments and they are accessed by 5 icons in the bottom navigation. However, one of the sections (Lessons) is now being replaced by a different fragment which contains a recycler view. Under this new design, one of the items in the recycler view will call the Lessons fragment.
The question is, how can I call the Lessons fragment from within the Recycler View contained in the new fragment?
Usually inside a recycler view I'd use code like the following:
@Override
public void onClick(View v) {
int index = getAdapterPosition();
LessonItem item = lessonList.get(index);
Intent intent = new Intent(context, SomeActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("lesson", item);
intent.putExtras(bundle);
((Activity) context).startActivityForResult(intent, 1);
}
but in this case I'm not dealing with an activity. Is there a way I can accomplish this without having to convert the fragment to an activity?
CodePudding user response:
As ismailfarisi mentioned before, if you use Navigation Component, it makes the transition easier.
However, if you want to still manage fragment replacements manually, you can interfaces as callback.
interface LessonItemListener {
void onItemClick(LessonItem item);
}
in your recycler view adapter
class YourAdapter {
public YourAdapter(LessonItemListener listener) {
this.listener = listener;
}
private LessonItemListener listener;
...
@Override
public void onClick(View v) {
int index = getAdapterPosition();
LessonItem item = lessonList.get(index);
listener.onItemClick();
}
}
in your fragment has recyclerview
class YourFragment {
private LessonItemListener listener;
public void setListener(LessonItemListener listener) {
this.listener = listener;
}
private void setupRecyclerView() {
YourAdapter adapter = new YourAdapter(listener);
recyclerView.setAdapter(adapter);
}
}
in your Activity contains those fragments
class YourActivity extends AppCompatActivity implements LessonItemListener {
private void setupFragments() {
YourFragment fragment = new YourFragment();
fragment.setListener(this);
}
...
@Override
public void onItemClick(LessonItem item) {
//you are in activity now
//make whatever you want here
//such as fragment replacement in your bottom nav
}
}
CodePudding user response:
navigation component from jetpack is better for handling fragment transition
you can check this documentation https://developer.android.com/guide/navigation