动态加载fragment和实现fragment 之间的通信
程序员文章站
2022-05-14 18:00:38
...
相信大家都用过网易云音乐吧,ios版的有如下的功能:
点击底部一个按钮就切换一个界面,利用fragmentlayout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include layout="@layout/title"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="11"
android:id="@+id/frag">
</FrameLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1">
<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/left"
android:layout_weight="1"
android:gravity="center"
android:text="left"/>
<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/another"
android:layout_weight="1"
android:gravity="center"
android:text="another"/>
<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/right"
android:layout_weight="1"
android:gravity="center"
android:text="right"/>
</LinearLayout>
</LinearLayout>
新建的fragment类继承自Fragment(support。V4)
public class LeftFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.left_fragment,container,false);
Button btn = (Button)view.findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
RightFragment fragment = RightFragment.newInstance("hi");
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.add(R.id.frag,fragment);
transaction.commit();}
});
return view;
}
}
MainActivity中的replaceFragment()功能是用传入的fragment填充入FagmentLyaout中
FragmentManager fragmentManager = getSupportFragmentManager();
Transaction transaction = fragmentManager.beginTransaction();
transactiorag,fragment);
tra);
} ```
本例中是leftfragment和rightment实现通信,首先在rightfragghtfrag法`shuju代码片`ment中写个传入数据的静态方法
``` public static RightFragment newInstance(String text){
RightFragment rightFragment = new RightFragment();
Bundle bundle = new Bundle();
bundle.putString("HELLO",text);
rightFragment.setArguments(bundle);
return rightFragment;
}```
在leftfragment中写入数据
RightFragment fragment = RightFragment.newInstance("hi");
“`的