You cannot pass a Bundle, but you CAN pass parameters (or rather attributes) through an XML fragment.
The process is similar to how you define the View custom attributes . Except AndroidStudio (currently) does not help you in this process.
suppose this is your fragment with arguments (I will use kotlin, but it works completely in Java too):
class MyFragment: Fragment() {
And you want to do something like this:
<fragment xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/myFragment" android:name="com.example.MyFragment" app:screen_name="@string/screen_a" android:layout_width="match_parent" android:layout_height="wrap_content"/>
Pay attention to the app:screen_name="@string/screen_a"
for this to work, just add this to the values file ( fragment_attrs.xml or select any name):
<attr name="screen_name" format="string|reference"/> <string name="screen_a" translatable="false">ScreenA</string> <string name="screen_b" translatable="false">ScreeenB</string> <declare-styleable name="MyFragment_MembersInjector"> <attr name="screen_name"/> </declare-styleable>
Almost done, you just need to read it in your fragment, so add a method:
override fun onInflate(context: Context?, attrs: AttributeSet?, savedInstanceState: Bundle?) { super.onInflate(context, attrs, savedInstanceState) if (context != null && attrs != null && screenName == null) { val ta = context.obtainStyledAttributes(attrs, R.styleable.MyFragment_MembersInjector) if (ta.hasValue(R.styleable.MyFragment_MembersInjector_screen_name)) { screenName = ta.getString(R.styleable.MyFragment_MembersInjector_screen_name) } ta.recycle() } }
et voilá, your XML attributes in your fragment :)
Limitations:
- Android Studio (at the moment) does not autocomplete such arguments in the XML layout
- You cannot pass
Parcelable but only what can be defined as Android attributes
Daniele Segato Sep 13 '18 at 7:42 2018-09-13 07:42
source share