I have an activity which instantiates and populates a Fragment through a adopter class. I want to pass values/objects to this Fragment adopter class so that i can dictate la
It's hard to say without seeing the logcat, but surely you are missing to call the commit()
method on the FragmentTransaction
. Also remember to set the arguments to the fragment before calling ft.commit()
.
@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
mFragment = (LayoutFragment) getSupportFragmentManager().findFragmentByTag(mTag);
if (mFragment == null) {
Bundle bundle = new Bundle();
bundle.putInt("noTiles", 4);
mFragment = (LayoutFragment) LayoutFragment.newInstance(mLayoutId);
mFragment.setArguments(bundle);
//ft.add(R.id.content, mFragment, mTag).commit();
ft.add(R.id.content, mFragment, mTag);
} else {
ft.attach(mFragment);
}
mSelectedLayoutId = mFragment.getLayoutId();
}
To pass argument to your fragment, it's recommended to create a public static method to instanciate your fragment like :
public static MyFragment newInstance(String firstArg) {
MyFragment f = new MyFragment ();
Bundle args = new Bundle();
args.putString("ARG1", firstArg);
f.setArguments(args);
return f;
}
And then retrieve your args in onCreateView()
method like :
String arg = getArguments().getString("ARG1");
Use the static method to instanciate a new fragment with your arguments in other fragment or activities like :
MyFragment f = MyFragment.newInstance(myArg);
In your activity
Bundle args = new Bundle();
args.putString("Menu", "Your String");
Fragment detail = new FragmeantOne();
detail.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, detail).commit();
In your Fragment.. in onCreateView()
String menu = getArguments().getString("Menu");
someTextView.setText(menu);
You can use Bundle to transfer data from activity to fragments or transfre data from fragment to fragment.
Bundle bundle = new Bundle();
DisplayDataList fragment = new DisplayDataList();
bundle.putString("listitem", "Buyer,Seller");
fragment.setArguments(bundle);
getFragmentManager().beginTransaction().replace(
R.id.frame_container, fragment).addToBackStack(null).commit();
Where you want to recieve that bundle i.w in DisplayDataList
Fragment class. You have to use getArguments()
method.
DisplayDataList
Bundle bundle = getArguments();
String getdata = bundle.getString("listitem");
System.out.println("Data got-->>> " + getdata);
Hope this will help you.