文章标题
2017-10-12 09:27
513 查看
创建布局文件-配置CrimeListFragment视图
视图和fragment的关联-
布局提供了一个 用来放置fragment的FrameLayout容器视图。
其中fragment可以在activity中使用代码获得。
但是 布局文件并没有特别指定fragment,因此对任何activity托管fragment,都可以使用这个布局文件。
定义抽象基类,完成从容器获取fragment的工作
每个Activity类都继承自这个抽象基类
RecyclerView类的任务 :回收再利用以及定位屏幕上的TextView视图。
定位的任务被委托给了LayoutManager,LayoutManger除了在屏幕上定位列表项,还否则定义屏幕滚动行为。
LinearLayoutManager 支持以竖直列表的形式展示列表项
GridLayoutManager 以网格的形式展示列表项
实现ViewHolder
视图和fragment的关联-
布局提供了一个 用来放置fragment的FrameLayout容器视图。
其中fragment可以在activity中使用代码获得。
但是 布局文件并没有特别指定fragment,因此对任何activity托管fragment,都可以使用这个布局文件。
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/fragment_container" android:layout_width="match_parent" android:layout_height="match_parent" > </FrameLayout>
定义抽象基类,完成从容器获取fragment的工作
public abstract class SingleFragmentActivity extends FragmentActivity { //返回由activity托管的fragment protected abstract Fragment createFragment(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fragment); //1.获取FragmentManager FragmentManager fragmentManager = getSupportFragmentManager(); //2.使用容器视图资源ID向FragmentManager请求并获取fragment Fragment fragment = fragmentManager.findFragmentById(R.id.fragment_container); //3.如果fragment为null,新建fragment并交由FragmentManager管理 if (fragment == null) { //新建fragment fragment = createFragment(); // 把fragment交由FragmentManager管理:创建一个新的fragment事务,加入一个添加操作,然后提交该事务 fragmentManager.beginTransaction().add(R.id.fragment_container, fragment).commit(); } } }
每个Activity类都继承自这个抽象基类
public class CrimeActivity extends SingleFragmentActivity { @Override protected Fragment createFragment() { return new CrimeFragment(); } }
RecyclerView
添加RecycleView 依赖库RecyclerView类的任务 :回收再利用以及定位屏幕上的TextView视图。
定位的任务被委托给了LayoutManager,LayoutManger除了在屏幕上定位列表项,还否则定义屏幕滚动行为。
LinearLayoutManager 支持以竖直列表的形式展示列表项
GridLayoutManager 以网格的形式展示列表项
//创建RecycleView视图 mCrimeRecycleView = (RecyclerView) view.findViewById(R.id.crime_recycler_view); //把RecycleView视图交给LayoutManager对象 mCrimeRecycleView.setLayoutManager(new LinearLayoutManager(getActivity()));
实现ViewHolder
public class CrimeListFragment extends Fragment { …… //定义ViewHolder 内部类 private class CrimeHolder extends RecyclerView.ViewHolder { public TextView mTitleTextView; public CrimeHolder(View itemView) { super(itemView); mTitleTextView = (TextView) itemView; } } }