I understand how to define custom attributes for a fragment and specify their values in XML (as in this answer). But I'm not sure how to do this for fragments that are dynamically created in Activity.onCreate()
. How do I provide the attribute values so that the fragment can get them by calling Context.obtainStyledAttributes()
in its onInflate()
?
Asked
Active
Viewed 599 times
1

Community
- 1
- 1

Andy Johnson
- 7,938
- 4
- 33
- 50
2 Answers
1
How do I provide the attribute values
You need to make your fragment handling arguments (see setArguments()) and then pass whatever you need to your newly created Fragment object, overriding XML or framgent defaults.

Marcin Orlowski
- 72,056
- 11
- 123
- 141
-
Hi Marcin. I understand how to do that (and its my current workaround) but using the arguments means that, if I want to the fragment to work if its created statically in xml or dynamically, I need to implement the attribute value handling twice. This doesn't seem right to me. – Andy Johnson Mar 02 '17 at 12:39
-
You can create separate setter methods for each attribute handled and pass data either from XML attributes of bundle to is for handling so you will have still one implementation. – Marcin Orlowski Mar 02 '17 at 12:40
-
`the attribute value handling twice` Using arguments is the only proper way as this deals with fragment reinstantiation automatically – Marcin Orlowski Mar 02 '17 at 12:42
0
Use the following code:
@Override
public void onInflate(Activity activity, AttributeSet attrs, Bundle savedInstanceState) {
super.onInflate(activity, attrs, savedInstanceState);
// Your code here to process the attributes
}

Husnain Aslam
- 865
- 1
- 11
- 28

Kshitij Gulati
- 19
- 5