If I declare a fragment in an XML layout, how do I pass it a Bundle?

前端 未结 6 788
南笙
南笙 2020-12-01 12:01

I\'ve got an activity that I\'ve replaced with a fragment. The activity took an Intent that had some extra information on what data the activity was supposed to display.

6条回答
  •  青春惊慌失措
    2020-12-01 12:03

    You can't pass a Bundle (unless you inflate your fragment programmatically rather then via XML) but you CAN pass parameters (or rather attributes) via XML to a fragment.

    The process is similar to how you define View custom attributes. Except AndroidStudio (currently) do not assist you in the process.

    suppose this is your fragment using arguments (I'll use kotlin but it totally works in Java too):

    class MyFragment: Fragment() {
    
        // your fragment parameter, a string
        private var screenName: String? = null
    
        override fun onAttach(context: Context?) {
            super.onAttach(context)
            if (screenName == null) {
                screenName = arguments?.getString("screen_name")
            }
        }
    }
    

    And you want to do something like this:

    
    

    Note the app:screen_name="@string/screen_a"

    to make it work just add this in a values file (fragment_attrs.xml or pick any name you want):

    
    
    
    
    ScreenA
    ScreeenB
    
    
    
    
        
    
    

    Almost done, you just need to read it in your fragment, so add the 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 (as of now) do not autocomplete such arguments in the layout XML
    • You can't pass Parcelable but only what can be defined as Android Attributes

提交回复
热议问题