安卓开发笔记基于同一activity之下的fragment之间传值功能的实现

示例:基于同一activityA之下的fragmentB与fragmentC之间传值的功能实现。


OnPassValueSelectedListener.class

public interface OnPassValueSelectedListener {
    
    
    public void putNameData(String value);
 }

accivityA.class:

public void putNameData(String value) {
    
    
    //封装数据
    Bundle bundle=new Bundle();
    bundle.putString("detail_name",value);
    FragmentC fragmentC=new FragmentC();
    //传递数据
    fragmentC.setArguments(bundle);
    getSupportFragmentManager()
            .beginTransaction()
            .add(R.id.fragment_container, fragmentC)
            .commit();
}

fragmentB.class:

private OnPassValueSelectedListener mListener;
String inputName=mEtName.getText().toString().trim();
if(inputName.length()==0) {
    
    
    Toast.makeText(getActivity(),"昵称不能为空", Toast.LENGTH_SHORT).show();
}else{
    
    
    mListener=(OnPassValueSelectedListener) getActivity();
    mListener.putNameData(inputName);
    //从栈中将当前fragment推出
    getFragmentManager().popBackStack();
}

fragmentC.class:

Bundle bundle =getArguments();
if(bundle!=null){
    
    
    String name=bundle.getString("detail_name");
}

activityA.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </FrameLayout>
</LinearLayout>

猜你喜欢

转载自blog.csdn.net/weixin_43319452/article/details/109356270