How to transfer some data to another Fragment?

前端 未结 10 1923
说谎
说谎 2020-11-22 11:41

How to transfer some data to another Fragment likewise it was done with extras for intents?

10条回答
  •  北海茫月
    2020-11-22 12:39

    Your input fragment

    public class SecondFragment extends Fragment  {
    
    
        EditText etext;
        Button btn;
        String etex;
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View v = inflater.inflate(R.layout.secondfragment, container, false);
            etext = (EditText) v.findViewById(R.id.editText4);
            btn = (Button) v.findViewById(R.id.button);
            btn.setOnClickListener(mClickListener);
            return v;
        }
    
        View.OnClickListener mClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
    
    
                etex = etext.getText().toString();
                FragmentTransaction transection = getFragmentManager().beginTransaction();
                Viewfragment mfragment = new Viewfragment();
                //using Bundle to send data
                Bundle bundle = new Bundle();
                bundle.putString("textbox", etex);
                mfragment.setArguments(bundle); //data being send to SecondFragment
                transection.replace(R.id.frame, mfragment);
                transection.isAddToBackStackAllowed();
                transection.addToBackStack(null);
                transection.commit();
    
            }
        };
    
    
    
    }
    

    your view fragment

    public class Viewfragment extends Fragment {
    
        TextView txtv;
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View v = inflater.inflate(R.layout.viewfrag,container,false);
            txtv = (TextView)  v.findViewById(R.id.textView4);
            Bundle bundle=getArguments();
            txtv.setText(String.valueOf(bundle.getString("textbox")));
            return v;
        }
    
    
    }
    

提交回复
热议问题