How to use setArguments() and getArguments() methods in Fragments?
You have a method called getArguments()
that belongs to Fragment
class.
How to get the getArguments data from a fragment?
I always pass data like this and work perfectly :
public class CategoryResultFragment extends BaseListFragment {
private static final String CATEGORY_ID = "EXTRA_CATEGORY_ID";
private static final String CATEGORY_SLUG = "EXTRA_CATEGORY_SLUG";
private String mCategoryId;
private String mCategorySlug;
public static CategoryResultFragment newInstance(String categoryId, String categorySlug) {
Bundle bundle = new Bundle();
bundle.putString(CATEGORY_ID, categoryId);
bundle.putString(CATEGORY_SLUG, categorySlug);
CategoryResultFragment categoryResultFragment = new CategoryResultFragment();
categoryResultFragment.setArguments(bundle);
return categoryResultFragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (getArguments() != null) {
mCategoryId = getArguments().getString(CATEGORY_ID);
mCategorySlug = getArguments().getString(CATEGORY_SLUG);
}
return super.onCreateView(inflater, container, savedInstanceState);
}
}
Set arguments of fragment from activity
AFAIK, you can't use setArguments()
like that when you embed the fragment within XML. If it's critical, you'd be better off dynamically adding the fragment instead. However if you truly want the fragment to be embedded via XML, there are different ways you can pass along that data.
- Have the Activity implement the fragment's event listener. Have the fragment then request the required parameters from the Activity at creation or whenever needed. Communication with Fragment
- Create custom attributes that can be embedded in xml along with the fragment. Then during fragment's inflation process, parse the custom attributes to obtain their data. Custom fragment attributes
- Create public setters in the fragment and have the activity use them directly. If it's critical to set them prior to the fragment's
onCreate()
method, then do it from the activity'sonAttachFragment()
method.
How to pass and get value from fragment and activity
Here is the Android Studio proposed solution (= when you create a Blank-Fragment with File -> New -> Fragment -> Fragment(Blank) and you check "include fragment factory methods").
Put this in your Fragment:
class MyFragment: Fragment {
...
companion object {
@JvmStatic
fun newInstance(isMyBoolean: Boolean) = MyFragment().apply {
arguments = Bundle().apply {
putBoolean("REPLACE WITH A STRING CONSTANT", isMyBoolean)
}
}
}
}
.apply
is a nice trick to set data when an object is created, or as they state here:
Calls the specified function [block] with
this
value as its receiver
and returnsthis
value.
Then in your Activity or Fragment do:
val fragment = MyFragment.newInstance(false)
... // transaction stuff happening here
and read the Arguments in your Fragment such as:
private var isMyBoolean = false
override fun onAttach(context: Context?) {
super.onAttach(context)
arguments?.getBoolean("REPLACE WITH A STRING CONSTANT")?.let {
isMyBoolean = it
}
}
Enjoy the magic of Kotlin!
Android Fragment declared in layout, how to set arguments?
The best way would be to change the to FrameLayout and put the fragment in code.
public void onCreate(...) {
ScheduleDayFragment fragment = new ScheduleDayFragment();
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction()
.add(R.id.main_view, fragment).commit();
...
}
Here is the layout file
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
Are you worried this is going to reduce performance somehow?
How to transfer some data to another Fragment?
Use a Bundle
. Here's an example:
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.setArguments(bundle);
Bundle has put methods for lots of data types. See this
Then in your Fragment
, retrieve the data (e.g. in onCreate()
method) with:
Bundle bundle = this.getArguments();
if (bundle != null) {
int myInt = bundle.getInt(key, defaultValue);
}
Fragment - getArguments() returns an empty bundle
Activity and Fragment recreation is one of the points our team provide special attention. So this is some bullets we have in mind.
- Does the "will be retained across fragment destroy and creation" includes the scenario I described?
Take in mind "Don't keep Activities" is destroying your Activity when you go to background. Later the system will try to recover your last state recreating the last Activity and its fragments automatically.
Android will save the necessary information to recover its last state. So yes, your scenario should be covered.
- Does the "Don't keep activities" option can mess up with getArguments()/setArguments() if it is enabled?
Depending on your flow you could experiment some problems. When activity recreates savedInstanceState on the onCreate method will be not null. You should use this information to avoid recreating or reattach your fragment. The system will try to recover it for you, this is the reason why fragments must not have any constructor.
- Is there a way to test proper fragment creation/destroy besides the "Don't keep activities" option?
Using FragmentTransaction.
1 - Use FragmentTransaction to add your fragment to your activity without adding it to the backstack.
2 - Use FragmentTransaction to replace the previous fragment with other fragment (or maybe a new instance of the previous fragment). When a fragment is replaced by other and it is not added to the back stack android destroys it.
- What is the better approach to properly keep fragment's arguments "alive"? I could save them in the onSaveInstanceState() method, but would like to know if there are more options besides that.
Probably you don't need to keep the arguments bundle in your code. Android will do it for you. But it is a good practice to recover the bundle data in onAttach method (first method called when the fragment is going to be available on the screen) and store them as class attributes for later use.
How to pass Arguments to Fragment from Activity
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();
}
Related Topics
How to Detect Device Is Android Phone or Android Tablet
How to Set Time to Device Programmatically
Android: How to Make the Keypad Always Visible
Add Shadow to Custom Shape on Android
Android Notification Is Not Showing
Programmatically Getting the Gateway and Subnet Mask Details
Out of Memory Error Imageview Issue
Register Application Class in Manifest
How to Browse Localhost on Android Device
Firebase: Query to Exclude Data Based on a Condition
Device Not Detected in Eclipse When Connected with Usb Cable
How to Transfer an Image from Its Url to the Sd Card
Is There Any Limit of Bundle in Android
How to Build an Android Library with Android Studio and Gradle
Convert Arraylist<Mycustomclass> to JSONarray
In Android Edittext, How to Force Writing Uppercase
How to Open/Display Documents(.Pdf, .Doc) Without External App
Neither User 10102 Nor Current Process Has Android.Permission.Read_Phone_State