1.创建静态fragment
写一个类继承fragment
重写onCreateView();return view
private TextView tv_firstFrag;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.layout_firstfragment, null);
tv_firstFrag = (TextView) view.findViewById(R.id.tv_firstFrag);
tv_firstFrag.setText("在fragment给控件赋值");
return view;
}
<fragment这里name指向重写了fragment的方法
android:id="@+id/firstFragment"
android:name="comvvitamio.cc.com.myapplicationdosometest.FirstFragment"
android:layout_width="match_parent"
android:layout_height="200dp" />
如果要在Java代码中动态的
生成你的内容的话可以这样:
tv_first= (TextView) findViewById(R.id.tv_firstFrag);
tv_first.setText("activity_______>fragment");
2.动态生成一个fragment
1.用frameLayout占位置,之后会被替换
<!-- 声明碎片的位置,待会会被替换 -->
<FrameLayout
android:id="@+id/replaceId"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_below="@id/firstFragment" />
2.写一个类来继承fragment与静态那边基本一样
3.在activity中动态试使用
一个事物只能被提交一次
fragmentManager=getFragmentManager();
FragmentTransaction transaction=fragmentManager.beginTransaction();
SecondFragment fragment=new SecondFragment();
transaction.replace(R.id.replaceId,fragment);
transaction.commit();
与静态一样,如果没有
动态生成内容的话,就是XML里面的内容,动态添加也可以
一个完整的动态例子
//一个事务只能被提交一次
FragmentTransaction beginTransaction = manager.beginTransaction();
BottomFragment fragment = new BottomFragment();
Bundle bundle = new Bundle();
bundle.putString("msg", content+new Date());
//传递内容到fragment里面
fragment.setArguments(bundle);
beginTransaction.replace(R.id.replaceId, fragment);
利用bundle传递数据的例子
Bundle bundle = new Bundle();
bundle.putString("msg", content+new Date());
//传递内容到fragment里面
fragment.setArguments(bundle);
Bundle bundle = getArguments();
if (bundle != null) {
String string = bundle.getString("msg");
tv_bottom.setText(string);
}
fragment的生命周期
---------------->自己去看吧,现在不想搞。看了记得补充笔记
对于一个动态fragment之间互相传递数据的例子
step1:
private FragmentManager manager;
step2:
manager=getFragmentManager();主函数的方法
FragmentTransaction transaction=manager.beginTransaction();
transaction.add(R.id.leftReplaceId,new LeftFragment());
transaction.add(R.id.rightRepaceId,new RightFragment());
transaction.commit();
public void doFileStr(String s){
FragmentTransaction transaction=manager.beginTransaction();
RightFragment fragment=new RightFragment();
Bundle bundle=new Bundle();
bundle.putString("msg",s);
fragment.setArguments(bundle);
transaction.replace(R.id.rightRepaceId,fragment);
transaction.commit();
点击发送左边fragment的数据
fileStr="xxxxxxxxxxxxxxx";
LeftAndRightFragment fragment= (LeftAndRightFragment) getActivity();
fragment.doFileStr(fileStr);
右边对数据的处理与显示
textView = (TextView) view.findViewById(R.id.textView);
Bundle bundle = getArguments();
if (bundle != null) {
String msg = bundle.getString("msg");
textView.setText(msg);
}