Android Studio中Fragment内嵌RecyclerView导致应用崩溃问题求助
问题原因
从LogCat输出可以定位到崩溃根因为空指针异常:你在Fragment1的onCreateView方法中调用recyclerView.setLayoutManager()时,recyclerView对象为null。
产生空指针的核心问题是布局引用错误:
- 你在Fragment的
onCreateView中加载的是R.layout.rows,这个布局是你给RecyclerView列表项用的单条布局,内部只有TextView控件,不存在id为RecyclerView2的RecyclerView控件,调用findViewById自然返回null。 - 除此之外你的MainActivity存在冗余代码:两次调用
setContentView,第一次加载activity_main布局后查找的recyclerView没有任何实际用途,后续又替换为新建的FrameLayout作为根布局。
修复步骤
- 新建Fragment专属布局文件,比如命名为
fragment_1.xml,内容如下:
<?xml version="1.0" encoding="utf-8"?> <androidx.recyclerview.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/RecyclerView2" android:layout_width="match_parent" android:layout_height="match_parent"/>
- 修改Fragment1的
onCreateView逻辑,将加载的布局替换为新建的Fragment布局:
@Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // 这里把原来的R.layout.rows换成R.layout.fragment_1 View view = LayoutInflater.from(getContext()).inflate(R.layout.fragment_1,container,false); RecyclerView recyclerView = view.findViewById(R.id.RecyclerView2); ImrulsAdapter Adapter = new ImrulsAdapter(getContext(),Text); recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); recyclerView.setAdapter(Adapter); return view; }
- 清理MainActivity中的冗余代码,修改后代码如下:
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FrameLayout frameLayout = new FrameLayout(this); frameLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT)); frameLayout.setId(R.id.layout); setContentView(frameLayout); getSupportFragmentManager().beginTransaction().add(R.id.layout,new Fragment1()).commit(); } }
- 确认你的列表项布局
R.layout.rows中存在id为textView的TextView控件,保证Adapter渲染逻辑正常。
内容的提问来源于stack exchange,提问作者Imrul Anwar
相关产品推荐
相关产品推荐

