我在我的 android studio 專案中做一個回收器方法,但我有一個問題。
每次我嘗試findViewById我的應用程式時都會崩潰。
Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
我不明白為什么,因為我正在以一種好的方式創造我的觀點??。
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_carrito, container, false);
return view;
}
我正在嘗試繼續
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
...
Log.e("test : ",Integer.toString(R.id.recyclerBuy));
recyView = view.findViewById(R.id.recyclerBuy);
/* recyView.setLayoutManager(new GridLayoutManager(getContext(),RecyclerView.VERTICAL));
recyView.setAdapter(buyAdapter);
*/
}
但我正在排隊recyView = view.findViewById(R.id.recyclerBuy);。我的 R.id.recyclerBuy 不是空的。
這是我的 RecyclerView
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".ui.carrito.CarritoFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="@ id/recyclerBuy"
android:layout_width="match_parent"
android:layout_height="550dp"
android:layout_marginBottom="88dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent" />
...
</androidx.constraintlayout.widget.ConstraintLayout>
任何人都知道為什么我每次都崩潰?
uj5u.com熱心網友回復:
發生這種情況是因為onAttach()之前呼叫了回呼onCreateView()。
解決此問題的最簡單方法是將代碼放在您RecyclerView在onCreateView(). 就像是:
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_carrito, container, false);
recyView = view.findViewById(R.id.recyclerBuy);
// here you recyView won't be null
return view;
}
一篇關于片段生命周期的好文章:https ://medium.com/androiddevelopers/the-android-lifecycle-cheat-sheet-part-iii-fragments-afc87d4f37fd
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/480740.html
標籤:爪哇 安卓工作室 android-recyclerview
下一篇:有沒有辦法獲得每個玩家的排名?
