横竖屏切换改变
int width = getWindowManager().getDefaultDisplay().getWidth();
int height = getWindowManager().getDefaultDisplay().getHeight();
Fragment1 fragment1 = new Fragment1();
Fragment2 fragment2 = new Fragment2();
//定义片段管理器
FragmentManager fm=getFragmentManager();
//定义片段事务处理
FragmentTransaction ft=fm.beginTransaction();
//判断横竖屏
if(width>height){
ft.replace(android.R.id.content, fragment1);
}else{
ft.replace(android.R.id.content, fragment2);
}
ft.commit();
Activity向Fragment传数据
// 创建Bundle,准备向Fragment传入参数
Bundle arguments = new Bundle();
arguments.putInt(BookDetailFragment.ITEM_ID, id);
// 创建BookDetailFragment对象
BookDetailFragment fragment = new BookDetailFragment();
// 向Fragment传入参数
fragment.setArguments(arguments);
// 使用fragment替换book_detail_container容器当前显示的Fragment
getFragmentManager().beginTransaction()
.replace(R.id.book_detail_container, fragment)
.commit();
Fragment获取数据
if (getArguments().containsKey(ITEM_ID))
{
book = BookContent.ITEM_MAP.get(getArguments()
.getInt(ITEM_ID)); //①
}
Fragment显示布局文件
// 重写该方法,该方法返回的View将作为Fragment显示的组件
@Override
public View onCreateView(LayoutInflater inflater
, ViewGroup container, Bundle savedInstanceState)
{
// 加载/res/layout/目录下的fragment_book_detail.xml布局文件
View rootView = inflater.inflate(R.layout.fragment_book_detail,
container, false);
if (book != null)
{
// 让book_title文本框显示book对象的title属性
((TextView) rootView.findViewById(R.id.book_title))
.setText(book.title);
// 让book_desc文本框显示book对象的desc属性
((TextView) rootView.findViewById(R.id.book_desc))
.setText(book.desc);
}
return rootView;
}
FragmentTransaction调用commit()方法之后,要你重新调用fragmentManager的beginTransaction()方法
fragmentManager=getFragmentManager();
abnormalFragment=new ExecuteAbnormalFragment();
normalFragment = new ExecuteNormalFragment();
status=(RadioGroup)findViewById(R.id.status);
status.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup arg0, int checkedId) {
fragmentTransaction=fragmentManager.beginTransaction();
if(checkedId==R.id.abnormal){
Toast.makeText(getApplicationContext(), "不正常", Toast.LENGTH_SHORT).show();
fragmentTransaction.replace(R.id.status_show, abnormalFragment);
//整体语句执行方法 getFragmentManager().beginTransaction().replace(R.id.status_show, abnormalFragment).commit();
}else{
Toast.makeText(getApplicationContext(), "正常", Toast.LENGTH_SHORT).show();
fragmentTransaction.replace(R.id.status_show, normalFragment);
// getFragmentManager().beginTransaction().replace(R.id.status_show, normalFragment).commit();
}
fragmentTransaction.commit();
}
});
}