Fragment是在API 11(Android3.0)引入的,为了可以支持适配宽屏设备,提供灵活多变的UI设计。php
Fragment是嵌在Activity里面可以交互的用户界面,它的存在必须依赖于Activity,不能独立存在。java
多个Activity能够复用同一个Fragment。一个Activity能够嵌入多个Fragment。android
Fragment的生命周期如上图所示。api
加入Activity的话则如上图所示。app
若是不加入Activity的生命周期的话,则为: onAttach()->onCreate()->onCreateView()->onStart()->onResume()->Fragment处于活动状态 onPause()->onStop()->onDestroyView()->onDestroy()->onDetach()ide
其中onDestroyView()->onCreateView(),发生此种状况的条件是当Fragment从回退栈(back stack)返回时才会发生。例如:Activity启动了Fragment A,而后又启动了FragmentB替换了Fragment A并把A添加到回退栈,当B返回后,退回到A,A的生命周期从onDestroyView()->onCreateView()开始。布局
onCreate(),能够在这里进行初始化this
onCreateView(),开始对Fragment界面进行绘制,须要返回一个View,一般为Fragment的布局。spa
onPause(),当调用到此方法时,说明用户正在离开Fragment,在这里须要对数据和状态进行保存设计
启动:
一般的只须要继承实现Fragment类,为了保证兼容性,通常使用support包的Fragment。
public class BaseFragment extends Fragment{
onCreate(){
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_article_list, container, false);
}
}
复制代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent">
<fragment android:name="com.example.news.ArticleListFragment" android:id="@+id/list" android:layout_weight="1" android:layout_width="0dp" android:layout_height="match_parent" />
<fragment android:name="com.example.news.ArticleReaderFragment" android:id="@+id/viewer" android:layout_weight="2" android:layout_width="0dp" android:layout_height="match_parent" />
</LinearLayout>
复制代码
其中中的android:name属性的值为Fragment的类全名。
此时Activity可直接加载布局中的Fragment
为了给Fragment设定一个惟一的标识,可使用以下两种方式:
设置惟一标识能够对数据恢复有帮助。
能够经过指定Activity布局中的ViewGroup布局来放置Fragment。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent">
...
<FrameLayout android:id="@+id/fl_fragment" android:layout_width="match_parent" android:layout_height="wrap_content"/>
...
</LinearLayout>
复制代码
Activity建议使用扩展包中的FragmentActivity的子类
public class BaseActivity extends FragmentActivity{
...
//获取FragmentTransaction
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
...
//添加Fragment
BaseFragment fragment = new BaseFragment();
fragmentTransaction.add(R.id.fl_fragment, fragment);
fragmentTransaction.commit();
...
}
复制代码
此外,还能够经过FragmentTransaction的add的重载方法add(Fragment fragment,String tag)添加无界面的Fragment。此时的tag参数为Fragment的标识ID,要取惟一值。而且不须要实现onCreateView()。因为此时Fragment无界面,因此不会对Activity的当前界面形成影响。
若是须要获取到无界面Fragment,可使用fragmentManager.findFragmentByTag(tag)。
可使用FragmentTransaction对Fragment进行管理,进行
操做完后必须调用commit()才会生效。
一次典型的操做:
Fragment newFragment = new BaseFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
//替换成新的Fragment
transaction.replace(R.id.fragment_container, newFragment);
//把当前的FragmentTransaction加入到回退栈
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
复制代码
transaction.addToBackStack(null);的做用是把当前FragmentTransaction加入到回退栈,当执行此代码并commit后,则点击回退键Activity不会直接结束,而是返回到Activity界面
有几个点须要注意:
下图为Fragment的返回栈,当前的FragmentTransaction实例调用addToBackStack()并commit就会入栈:
返回的话会从栈顶开始返回,最上层的会销毁
一个Fragment的实例是和它所绑定的Activity实例牢牢关联的。Fragment能够经过getActivity()获取它所关联绑定的Activity。
宽屏布局 res/layout-land/fragment_layout.xml,用于大屏幕设备,好比平板电脑等:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent">
<fragment class="com.example.android.apis.app.FragmentLayout$TitlesFragment" android:id="@+id/titles" android:layout_weight="1" android:layout_width="0px" android:layout_height="match_parent" />
<FrameLayout android:id="@+id/details" android:layout_weight="1" android:layout_width="0px" android:layout_height="match_parent" android:background="?android:attr/detailsElementBackground" />
</LinearLayout>
复制代码
手机布局 res/layout/fragment_layout.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent">
<fragment class="com.example.android.apis.app.FragmentLayout$TitlesFragment" android:id="@+id/titles" android:layout_width="match_parent" android:layout_height="match_parent" />
</FrameLayout>
复制代码
TitlesFragment 的实现
public static class TitlesFragment extends ListFragment {
boolean mDualPane;
int mCurCheckPosition = 0;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// 添加文章列表
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_activated_1, Shakespeare.TITLES));
// 检查是否上图左边的那种布局(宽屏模式)
View detailsFrame = getActivity().findViewById(R.id.details);
mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;
if (savedInstanceState != null) {
// Restore last state for checked position.
mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
}
if (mDualPane) {
// In dual-pane mode, the list view highlights the selected item.
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
// Make sure our UI is in the correct state.
showDetails(mCurCheckPosition);
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curChoice", mCurCheckPosition);
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
showDetails(position);
}
/** * 若是是宽屏模式的话,则直接在右边的Fragment更新内容 * 若是不是宽屏模式,则跳转到新的Activity进行展现 */
void showDetails(int index) {
mCurCheckPosition = index;
if (mDualPane) {
getListView().setItemChecked(index, true);
DetailsFragment details = (DetailsFragment)
getSupportFragmentManager().findFragmentById(R.id.details);
if (details == null || details.getShownIndex() != index) {
details = DetailsFragment.newInstance(index);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if (index == 0) {
ft.replace(R.id.details, details);
} else {
ft.replace(R.id.a_item, details);
}
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
} else {
Intent intent = new Intent();
intent.setClass(getActivity(), DetailsActivity.class);
intent.putExtra("index", index);
startActivity(intent);
}
}
}
复制代码
DetailsFragment的实现:
public static class DetailsFragment extends Fragment {
public static DetailsFragment newInstance(int index) {
DetailsFragment f = new DetailsFragment();
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
public int getShownIndex() {
return getArguments().getInt("index", 0);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (container == null) {
// We have different layouts, and in one of them this
// fragment's containing frame doesn't exist. The fragment
// may still be created from its saved state, but there is
// no reason to try to create its view hierarchy because it
// won't be displayed. Note this is not needed -- we could
// just run the code below, where we would create and return
// the view hierarchy; it would just never be used.
return null;
}
ScrollView scroller = new ScrollView(getActivity());
TextView text = new TextView(getActivity());
int padding = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
4, getActivity().getResources().getDisplayMetrics());
text.setPadding(padding, padding, padding, padding);
scroller.addView(text);
text.setText(Shakespeare.DIALOGUE[getShownIndex()]);
return scroller;
}
}
复制代码
若是是手机的状况,跳转到新的Activity:
public static class DetailsActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation
== Configuration.ORIENTATION_LANDSCAPE) {
// If the screen is now in landscape mode, we can show the
// dialog in-line with the list so we don't need this activity.
finish();
return;
}
if (savedInstanceState == null) {
// During initial setup, plug in the details fragment.
DetailsFragment details = new DetailsFragment();
details.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add(android.R.id.content, details).commit();
}
}
}
复制代码
--End--