First Fragment Sending String To Next Fragment
public class MainActivity extends AppCompatActivity {
private Button Add;
private EditText edt;
FragmentManager fragmentManager;
FragClass1 fragClass1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Add= (Button) findViewById(R.id.BtnNext);
edt= (EditText) findViewById(R.id.editText);
Add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
fragClass1=new FragClass1();
Bundle bundle=new Bundle();
fragmentManager=getSupportFragmentManager();
fragClass1.setArguments(bundle);
bundle.putString("hello",edt.getText().toString());
FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.activity_main,fragClass1,"");
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
}
}
Next Fragment to fetch the string.
public class FragClass1 extends Fragment {
EditText showFrag1;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.lay_frag1,null);
showFrag1= (EditText) view.findViewById(R.id.edtText);
Bundle bundle=getArguments();
String a=getArguments().getString("hello");//Use This or The Below Commented Code
showFrag1.setText(a);
//showFrag1.setText(String.valueOf(bundle.getString("hello")));
return view;
}
}
I used Frame Layout easy to use.
Don't Forget to Add Background color or else fragment will overlap.
This is for First Fragment.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:background="@color/colorPrimary"
tools:context="com.example.sumedh.fragmentpractice1.MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editText" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:id="@+id/BtnNext"/>
</FrameLayout>
Xml for Next Fragment.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:background="@color/colorAccent"
android:layout_height="match_parent">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/edtText"/>
</LinearLayout>