用Fragment创建动态UI
创建Fragment
- 引入v4包或者v7包
创建一个Fragment类
- 需要重写关键的生命周期方法
与Activity不同的是,Fragment是回调onCreateView()来定义布局
public class ArticleFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.article_view, container, false); } }
使用XML为Activity添加一个Fragment
public class MainActivity extends FragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news_articles);
}
}
- v7包应该继承ActionBarActivity
构建合理的UI界面
- 使用FragmentManager去创建动态界面
在运行时为Activity添加Fragment
- 用FragmentManager创建FragmentTransaction
- 在Activity的onCreate()方法调用时初始化Fragments
Activity必须拥有View组件插入Fragment
getSupportFragmentManager().beginTransaction() .add(R.id.fragment_container, firstFragment).commit();
用一个Fragment替换另一个
为了让用户取消fragment的转换,在提交事务之前必须调用 addToBackStack()
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); // Replace whatever is in the fragment_container view with this fragment, // and add the transaction to the back stack so the user can navigate back transaction.replace(R.id.fragment_container, newFragment); transaction.addToBackStack(null); // Commit the transaction transaction.commit();
- addToBackStack()带一个指定的String参数,默认传递null
和其他Fragments进行通信
定义接口
public class HeadlinesFragment extends ListFragment {
OnHeadlineSelectedListener mCallback;
// Container Activity must implement this interface
public interface OnHeadlineSelectedListener {
public void onArticleSelected(int position);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (OnHeadlineSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
...
}
* Fragment可以调用onArticleSelected()方法来传递给Activity信息,activity需要实现接口
传递给Fragment信息
- 通过findViewById()直接调用Fragment的公有方法