我在我的活動onCreate
功能如下代碼:無法將LAYOUTManager設置爲RecyclerView。顯示空指針的RecyclerView
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayoutManager manager = new LinearLayoutManager(this);
manager.setOrientation(LinearLayoutManager.VERTICAL);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(manager);
setContentView(R.layout.my_layout);
// some more code
和my_layout.xml
如下所示:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/annonce.main.coordinator"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:ignore="RtlHardcoded">
<android.support.design.widget.AppBarLayout...>
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none"
app:behavior_overlapTop="78dp"
android:fillViewport="true"
android:layout_gravity="fill_vertical"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/card_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
card_view:cardCornerRadius="4dp">
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:choiceMode="singleChoice"
android:scrollbars="vertical"
app:behavior_overlapTop="78dp"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
</ListView>
</android.support.v7.widget.CardView>
</android.support.v7.widget.RecyclerView>
</android.support.design.widget.CoordinatorLayout>
我收到錯誤:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method void
android.support.v7.widget.RecyclerView.setLayoutManager(android.support.v7.widget.RecyclerView$LayoutManager) on a null object reference` in the line recyclerView.setLayoutManager(manager);
我確實嘗試過在以前的sof文章中的類似查詢,但沒有一個看起來像d解決我的問題很多。你能告訴我我的代碼在哪裏出錯嗎?謝謝。
移動'的setContentView(R.layout.my_layout);'到後'super.onCreate(savedInstanceState)頂部;' –
即引發錯誤'所致:java.lang.IllegalStateException:RecyclerView沒有LayoutManager'這是非常理由我在之前添加了'LinearLayoutManager'代碼。 –
對不起,我剛剛注意到。你的佈局是錯誤的。 RecyclerView只能包含由** RecylerViewAdapter **填充的視圖。檢查這個鏈接學習如何使用RecyclerView http://code.tutsplus.com/tutorials/getting-started-with-recyclerview-and-cardview-on-android--cms-23465 –