在fragment_crime_list.xml添加一个Textview
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/crime_recycle_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:icon="@drawable/ic_menu_add"/>
<TextView
android:id="@+id/crime_set_empty_text_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:textSize="20sp"
android:text="无犯错记录"/>
</RelativeLayout>
然后在 CrimeListFragment 中引用该 TextView
mEmptyTextView = (TextView) view
.findViewById(R.id.crime_set_empty_text_view);
最后,在 updateUI() 方法中,获取到数据集时,判断一下数据长度,如果大于零, 隐藏这个 TextView,然后执行之前的操作;如果为零,就隐藏 RecyclerView,显示该 TextView。
private void updateUI() {
CrimeLab crimeLab = CrimeLab.get(getActivity());
List<Crime> crimes = crimeLab.getCrimes();
if(crimes.size()>0) {
mEmptyTextView.setVisibility(View.INVISIBLE);
if (mAdapter == null) {
mAdapter = new CrimeAdapter(crimes);
mCrimeRecyclerView.setAdapter(mAdapter);
} else {
mAdapter.setCrimes(crimes);
mAdapter.notifyDataSetChanged();
}
}
else{
mCrimeRecyclerView.setVisibility(View.INVISIBLE);
mEmptyTextView.setVisibility(View.VISIBLE);
}
updateSubtitle();
}
}