I tried the code below, but it's not working . program crushed without giving me output. How can i send data from one fragment to another fragment in same activity? First time using fragment `
//first fragment
public class FirstFragment extends Fragment implements View.OnClickListener{
public FirstFragment() {
}
Button btnSend;
EditText etTextContainer;
Bundle b;
SecondFragment fragB;
View v;
FragmentTransaction fragmentTransaction;
Fragment fragment;
SecondFragment mfragment;
String etex;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v= inflater.inflate(R.layout.fragment_first2, container, false);
btnSend=(Button)v.findViewById(R.id.btnSend);
etTextContainer=(EditText)v.findViewById(R.id.etText);
btnSend.setOnClickListener(mClickListener);
return v;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
View.OnClickListener mClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
etex = etTextContainer.getText().toString();
FragmentTransaction transection = getFragmentManager().beginTransaction();
mfragment = new SecondFragment();
//using Bundle to send data
Bundle bundle = new Bundle();
bundle.putString("key", etex);
mfragment.setArguments(bundle); //data being send to SecondFragment
transection.replace(R.id.tvShowTxt, mfragment);
transection.isAddToBackStackAllowed();
transection.addToBackStack(null);
transection.commit();
}
};
@Override
public void onClick(View view) {
}
}
// second fragment
public class SecondFragment extends Fragment {
Bundle b;
TextView tvShowText;
String s;
View v;
public SecondFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v= inflater.inflate(R.layout.fragment_second, container, false);
tvShowText = (TextView) v.findViewById(R.id.tvShowTxt);
Bundle bundle=getArguments();
tvShowText.setText(String.valueOf(bundle.getString("key")));
return v;
}
}`
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…