1

嘗試使用片段內的recyclerview實現卡片列表。每次運行它時試圖打開片段崩潰。我正在按照這個教程https://developer.android.com/training/material/lists-cards.html#Dependencies,也是這一個http://code.tutsplus.com/tutorials/getting-started-with-recyclerview-and-cardview-on-android--cms-23465RecyclerView的NullPointerException在片段

Logcat它崩潰。

 
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setHasFixedSize(boolean)' on a null object reference 

circles_tab.xml片斷

<android.support.v7.widget.RecyclerView 
    android:id="@+id/circleList" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_marginLeft="12dp" 
    android:layout_marginRight="12dp" 
    android:layout_marginTop="12dp"/> 

CirclesFragment

public class CirclesFragment extends Fragment { 

public ArrayList<String> circles = new ArrayList<String>(); 
public CharSequence[] circlesList; 
public String[] circlesArray = new String[circles.size()]; 
private List<Person> persons; 


private RecyclerView mRecyclerView; 
private RecyclerView.Adapter mAdapter; 
private RecyclerView.LayoutManager mLayoutManager; 

ButtonFloat FAB; 
Dialog dialog; 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    View v =inflater.inflate(R.layout.circles_tab,container,false); 

    // Create Cards list 

    mRecyclerView = (RecyclerView)getActivity().findViewById(R.id.circleList); 
    mRecyclerView.setHasFixedSize(false); 
    mLayoutManager = new LinearLayoutManager(getActivity()); 
    mRecyclerView.setLayoutManager(mLayoutManager); 
    initializeData(); 
    mAdapter = new RVAdapter(persons); 
    mRecyclerView.setAdapter(mAdapter); 

    return v; 
} 

private void initializeData(){ 
    persons = new ArrayList<>(); 
    persons.add(new Person("Peter Parker", R.drawable.logo)); 
    persons.add(new Person("Miles Morales",R.drawable.logo)); 
    persons.add(new Person("Oliver Queen", R.drawable.logo)); 
} 

沒有與此主題相關的類似的問題,但大部分都沒有得到解決。任何幫助將不勝感激。

謝謝大家

回答

5

變化

mRecyclerView = (RecyclerView)getActivity().findViewById(R.id.circleList); 

mRecyclerView = (RecyclerView)v.findViewById(R.id.circleList); 
+1

太感謝您了! –

+0

謝謝。這幫助我解決了我的問題。 – viper