先看这样一段代码
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#555555">
android:id="@+id/titles"
android:layout_weight="1"
android:layout_width="0px"
android:layout_height="match_parent"
android:background="#00550033" />
android:layout_weight="2"
android:layout_width="0px"
android:layout_height="match_parent" />
程序运行图片如下:
这里有一个名为 的新标记,此标记拥有一个名为 class 的新特性,注意: 碎片不是视图组件! 所以会有这样的XML布局写法
标记只是此布局中的一个占位符,不能将子标记放在 标记内
标记的class特性指定应用程序 的标题的扩展类, 也就是必须写一个类 继承Fragment,碎片拥有自己的视图层次结构,该结构将由碎片在以后创建.
这里下一个标记是 FrameLayout,而不是 再写一个 标记. 为什么是这样呢?
稍后作讲解,首先应知道,将在详情文本上执行一些过渡,将一个碎片切换到另一个。使用FrameLayout 作为视图容器来持有当前的文本碎片,对于标题碎片,只需一个碎片,没有切换和过渡, 对于显示详情的区域, 将有多个碎片!
在这个应用中,要确定使用碎片,只需判断设备的方向, 如果处于横向模式, 则拥有多个窗格,那么将使用碎片来显示文本,将碎片定义为DetailsFragment,使用一种工厂方法来创建带有索引的Fragment,如果处于纵向模式,则没有多个窗格
主要代码
public boolean isMultiPane() { // 根据是否横屏,判断是否多个碎片
return getResources().getConfiguration().orientation
== Configuration.ORIENTATION_LANDSCAPE;
}
/**
* 用于显示选中条目的详情的方法, either by
* displaying a fragment in-place in the current UI,or starting a
* whole new activity in which it is displayed.
*/
public void showDetails(int index) {
Log.v(TAG,"in MainActivity showDetails(" + index + ")");
if (isMultiPane()) {
// Check what fragment is shown,replace if needed.
DetailsFragment details = (DetailsFragment) getSupportFragmentManager().findFragmentById(R.id.details);
if (details == null || details.getShownIndex() != index) {
// Make new fragment to show this selection.
details = DetailsFragment.newInstance(index);
// Execute a transaction,replacing any existing
// fragment with this one inside the frame.
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.setCustomAnimations(android.R.anim.fade_in,android.R.anim.fade_out);
//ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.replace(R.id.details,details);
//ft.addToBackStack(TAG);
ft.commit();
//getSupportFragmentManager().executePendingTransactions();
}
} else {
// 否则加载一个新的Activity用于显示被选中文本的对话框碎片
Intent intent = new Intent();
intent.setClass(this,DetailsActivity.class);
intent.putExtra("index",index);
startActivity(intent);
}
}
总结
如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
小编个人微信号 jb51ccc
喜欢与人分享编程技术与工作经验,欢迎加入编程之家官方交流群!