public abstract class SingleFragmentActivity extends FragmentActivity {
protected abstract Fragment createFragment();
@Override
public 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();
}
}
}
从activity_fragment.xml布局里实例化activity视图,然后在容器中查找FragmentManager里的fragment。如果找不到,就新建fragment并将其添加到容器中。
1、新建一个模拟太阳的drawable资源(sun.xml):
<?xml version="1.0" encoding="utf-8"?>