2015-05-04 45 views
4

我最近開始使用RecyclerView替換舊的ListView。但每當我在android.support.v7.widget.RecyclerView元素使用android:scrollbars="vertical",我有以下錯誤應用程序崩潰: Attempt to invoke virtual method 'boolean android.support.v7.widget.RecyclerView$LayoutManager.canScrollVertically()' on a null object reference在RecyclerView中設置滾動條屬性導致我的應用程序崩潰

這是我如何使用RecyclerView:

View rootView; 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    rootView = inflater.inflate(R.layout.my_fragment, container, false); 
    return rootView; 
} 
protected void onPostExecute(Boolean result) { 
    RecyclerView rv = (RecyclerView) rootView.findViewById(R.id.recyclerview); 
    LinearLayoutManager llm = new LinearLayoutManager(context); 
    rv.setLayoutManager(llm); 
    RecycleViewAdapter adapter = new RecycleViewAdapter(myRecyclerViewAdapter); 
    rv.setHasFixedSize(true); 
    rv.setAdapter(adapter); 
} 

這是my_fragment.xml文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical"> 

    <android.support.v7.widget.RecyclerView 
     android:id="@+id/recyclerview" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:scrollbars="vertical"> 

    </android.support.v7.widget.RecyclerView> 

</LinearLayout> 

如果我不使用android:scrollbars="vertical",一切正常。謝謝你的幫助。

+0

檢查此鏈接http://stackoverflow.com/questions/27056379/is-there-any-way-to-enable-scrollbars-for-recyclerview-in-code –

+0

@JigneshJain我也嘗試添加' android:scrollbars =「vertical」'它會崩潰我的應用程序,就像問題中提到的那樣。 –

+0

檢查此https://code.google.com/p/android/issues/detail?id=78545 –

回答

0

使用RecyclerView時,您並不需要指定scrollbars顯示;它是LayoutManager作業,您可以指定它是垂直還是水平方向,當然滾動條顯示會自動更改您選擇的任何方向。

//for vertical scrollbar and orientation 
LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false); 

//for horizontal scrollbar and orientation 
LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false); 
+0

我剛試過,它仍然不顯示滾動條。 –

+0

@BasitSaeed列表有多大?有一個滾動條足夠大嗎? –

+0

它有7個元素,是的,當內容溢出時,它具有足夠大的滾動條。 –