Android学习笔记(十一)——将Fragment添加到Activity中以及参数传递
程序员文章站
2022-05-31 20:25:36
...
将Fragment添加到Activity中
Fragment的布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<TextView
android:id="@+id/tv_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#000"
android:text="我是AFragment"
android:textSize="20sp"
android:gravity="center"/>
</LinearLayout>
Activity的布局文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:id="@+id/btn_change"
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="更换fragment"
/>
<FrameLayout //用于放置Fragment
android:id="@+id/fl_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/btn_change"/>
</RelativeLayout>
将这个AFragment添加到Activity中去,通过Activity中的java代码
private AFragment mAFragment;
//实例化AFragment
mAFragment=new AFragment();
//将AFragment添加到activity中去,记得调用commit
getSupportFragmentManager()beginTransaction().add(R.id.fl_container,mAFragment).commitAllowingStateLoss();
效果显示:
点击按钮将AFragment切换成BFragment
mbtnChange=(Button)findViewById(R.id.btn_change);
mbtnChange.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(mBFragment==null){
mBFragment=new BFragment();
}
getSupportFragmentManager().beginTransaction().replace(R.id.fl_container,mBFragment).commitAllowingStateLoss(); //这里将add方法换成replace方法
}
});
效果展示:
参数传递——通过setArguements()
注意:不能直接写一个带参数的构造函数来传递参数
在AFragment中的java代码:
public class AFragment extends Fragment {
private TextView mTvtitle;
// private Activity mActivity;
public static AFragment setInstance(String title){ //Fragment传递参数
AFragment afragment=new AFragment();
Bundle bundle=new Bundle();
bundle.putString("title",title);
afragment.setArguments(bundle);
return afragment;
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.fragment_a,container,false); //找到布局文件
//return super.onCreateView(inflater, container, savedInstanceState);
return view;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mTvtitle=(TextView)view.findViewById(R.id.tv_title); //找到组件
if(getArguments()!=null){
mTvtitle.setText(getArguments().getString("title")); //得到传递的参数
}
}
}
在Activity的java代码中:
mAFragment=AFragment.setInstance("我是参数"); //通过setInstance设置参数
//将AFragment添加到activity中去,记得调用commit
getSupportFragmentManager().beginTransaction().add(R.id.fl_container,mAFragment).commitAllowingStateLoss();
效果显示:
上一篇: CSS选择文本颜色修改
下一篇: 用HTML和CSS在输入框前面加图标