使用抽象activity托管fragment
为CrimeListActivity创建视图,通用的布局定义文件
<FrameLayout android:id="@+id/fragment_container"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" />
为CrimeActivity更新布局文件引用
setContentView(R.layout.activity_fragment);
使用抽象activity类
1)创建一个Activity抽象类
public abstract class SingleFragmentActivity extends AppCompatActivity {}
2)添加一个通用超类
protected abstract Fragment createFragment();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragment_container);
if (fragment == null) {
fragment = createFragment();
fm.beginTransaction()
.add(R.id.fragment_container, fragment)
.commit();
}
}
3)清理CrimeActivity类
public class CrimeActivity extends SingleFragmentActivity {
@Override
protected Fragment createFragment() {
return new CrimeFragment();
}
}
4)新建两个控制类:CrimeListActivity和CrimeListFragment
public class CrimeListActivity extends SingleFragmentActivity {
@Override
protected Fragment createFragment() {
return new CrimeListFragment();
}
}
public class CrimeListFragment extends Fragment {}
声明CrimeListActivity为launcher activity
<activity android:name=".CrimeListActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>