Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a value from one Fragment to another in Android?

I am a newbie to Fragments. I want to pass a String value from one Fragment to another. how to do this? I have called my Fragments in the following way. please guide me step by step.

String cid = id.getText().toString();
Fragment fr = new FriendFragment();
android.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fr);
ft.commit(); 
like image 800
anu_r Avatar asked Apr 23 '14 16:04

anu_r


People also ask

How do I pass a value from one fragment to another?

So to share a string between fragments you can declare a static String in Activity. Access that string from Fragment A to set the value and Get the string value in fragment B. 2. Both fragments are hosted by different Activities- Then you can use putExtra to pass a string from Fragment A of Activity A to Activity B.

How will you pass data from one fragment to another fragment in Android using interface?

To pass data from one fragment to another Bundle will help. LifeShapeDetailsFragment fragment = new LifeShapeDetailsFragment(); // object of next fragment Bundle bundle = new Bundle(); bundle. putInt("position", id); fragment. setArguments(bundle);

How do I move an object from one fragment to another in Android?

Implements the override methods of Parcelable class. You can use Keyboard shortcut as: put cursor over Parcelable class and tap 'Alt, Enter' then click on Implement methods. This is how you Pass data to another Fragment. You can write this piece of code on the event where you want to replace the fragment.

How do you pass data from one fragment to another fragment in Kotlin?

Step 1 − Create a new project in Android Studio, go to File ⇉ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. Step 3 − Create two FragmentActivity and add the codes which are given below.


1 Answers

You can do something like below,

 String cid=id.getText().toString();
 Fragment fr=new friendfragment();
 FragmentManager fm=getFragmentManager();
 android.app.FragmentTransaction ft=fm.beginTransaction();
 Bundle args = new Bundle();
 args.putString("CID", cid);
 fr.setArguments(args);
 ft.replace(R.id.content_frame, fr);
 ft.commit(); 

To receive the data do the following,

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    String strtext = getArguments().getString("CID");    
    return inflater.inflate(R.layout.fragment, container, false);
}
like image 116
Spring Breaker Avatar answered Nov 01 '22 17:11

Spring Breaker