[英]new Fragment is not opening when recyclerView item is clicked
我一直試圖在點擊時啟動一個新片段,我在互聯網上發現這是這樣的,當點擊方法被激怒但沒有任何反應
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
}
對於 getCurrentPLace(),它是一種返回 Place Object 的方法,我已經用調試器檢查了它,它按預期工作
這是 DetailFragment.class 代碼
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;
}
}
這是 ID 為 R.id.tabItem 的 XML
<?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:我嘗試了類似問題的解決方案,但沒有任何效果。
一開始最好的方法是使用接口。
Interface onClick{
void click();
}
並在 class 的構造函數中實現它:
class PlacesRecyclerAdapter(onClick click)...
並像使用它一樣
t.setOnClickListener{
click.click();
}
當您在活動中定義適配器時,此方法(單擊)實現,您可以在活動中定義它而不是適配器
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();
但避免這些問題的最好方法是使用導航組件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.