2015-05-04 165 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个元素,是的,当内容溢出时,它具有足够大的滚动条。 –