我试图在AppCompatActivity的ViewPager中的 fragment 中创建ListView。在AppCompatActivity中,所有 View 元素都包装在CoordinatorLayout中。因为我使用了CoordinatorLayout。我必须使用RecylerView,我正在尝试遵循以下培训
developer.android.com,但是登录后我的应用程序停止了。这是我在myFragment中应用程序停止的代码。
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
//...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_city_list, container, false)
mRecyclerView = (RecyclerView) view.findViewById(android.R.id.list);
mLayoutManager = new LinearLayoutManager(this.getActivity());
Log.d("debugMode", "The application stopped after this");
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new RecyclerAdapter(getNames());
mRecyclerView.setAdapter(mAdapter);
return view;
}
//...
最佳答案
用这个
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_city_list, container, false)
// Replace 'android.R.id.list' with the 'id' of your RecyclerView
mRecyclerView = (RecyclerView) view.findViewById(android.R.id.list);
mLayoutManager = new LinearLayoutManager(this.getActivity());
Log.d("debugMode", "The application stopped after this");
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new RecyclerAdapter(getNames());
mRecyclerView.setAdapter(mAdapter);
return view;
}
您应该在
setLayoutManager
上调用setAdapter
和Recyclerview
方法(分别为和)。加,
您不应该使用
android.R.id.list
,因为您没有使用ListFragment
。用您的id
的Recyclerview
替换它(如您的XML布局一样)。关于java - 在 fragment 中实现RecyclerView,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34278892/