i've been trying to launch a new fragment on click, i found on the internet this is way, when clicking the methode gets provoked but nothing happens
public class PlacesRecyclerAdapter extends
RecyclerView.Adapter<PlacesRecyclerAdapter.ViewHolder> implements View.OnClickListener{
//some code
@Override
public void onClick(View v) {
AppCompatActivity activity = (AppCompatActivity) context;
TextView t = v.findViewById(R.id.placeName);
fragment = new DetailFragment(getCurrentPlace((String) t.getText()));
FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.tabItem, fragment);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.addToBackStack(null);
transaction.commit();
}
//some code
}
for the getCurrentPLace() it's a method that return a Place Object, i've checked it with the debbuger, and it works as expected
here is the DetailFragment.class code
public class DetailFragment extends Fragment {
private MainActivity.Place place;
TextView name;
public DetailFragment(MainActivity.Place place) {
this.place = place;
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.detail_place_fragment, container, false);
name.setText(place.getTitle());
return view;
}
}
here is the XML with the id R.id.tabItem
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/tabItem"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/placesRecycleView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
PS: i tried the solutions on the similair questions, but nothing worked.
The best way at first is to use Interface.
Interface onClick{
void click();
}
and implement it in the constructor of the class :
class PlacesRecyclerAdapter(onClick click)...
and use it like
t.setOnClickListener{
click.click();
}
and when you define the adapter in your activity, this method (click) implement and you can define this in the activity instead of the adapter
fragment = new DetailFragment(getCurrentPlace((String) t.getText()));
FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.tabItem, fragment);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.addToBackStack(null);
transaction.commit();
but the best way to avoid these problems is to use the navigation component.