创建列表明细应用1-使用fragment

笔记自《Android编程权威指南第二版》

第七章,创建一个列表明细应用

fragment是一种控制器对象,activity可委派它完成一些任务,这些任务通常就是管理用户界面。(管理用户界面的fragment又称UI fragment。它自己也产生布局文件)

利用fragment,可轻松实现选择不同的列表项就显示对应的明细视图Activity负责以一个明细fragment替换另一个明细fragment

托管可以这样理解,activity在其视图层级里提供一处位置来放置fragment的视图。fragment本身不具有在屏幕上显示视图的能力。

添加支持库:


dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:26.+'
compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha8'
testCompile 'junit:junit:4.12'
compile 'com.android.support:support-v4:26.0.0-alpha1'
compile 'com.android.support:recyclerview-v7:26.0.0-alpha1'
}

项目结构:

Crime实体类:

 View Code

SingleFragmentActivity抽象基类,用于CrimeActivity , CrimeListActivity。而这两个Activity又分别创建各自的Fragment

 View Code

CrimeActitiy.java

 View Code

CrimeListActivity.java

 View Code

activity_fragment.xml 的layout,用于托管fragment。很简单,就只放了一个FrameLayout,用于承载Fragment

 View Code

fragment_crime.xml布局:

 View Code

横向:

 View Code

CrimeFragment.java控制器,展示数据

 View Code

列表项的控制CrimeListFragment.java:

 View Code

数据从哪里来,单例的CrimeLab.java

 View Code

如果是显示列表呢,使用recyclerview,fragment_crime_list.xml布局:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/crime_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

其中列表项:list_item_crime.xml:

 View Code

当然先修改一下AndroidManifest.xml文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.homelink.testcriminal">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">

<activity android:name=".CrimeListActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".CrimeActivity">

</activity>
</application>

</manifest>

运行:

原文地址:https://www.cnblogs.com/ybsport/p/12340683.html