K
K
Kirill2018-09-23 16:57:21
Android
Kirill, 2018-09-23 16:57:21

How to pass string from Activity to Fragment and pass that string to textview?

I have MainActivity and BottomNavigationDrawerFragment
I need to pass a variable from MainActivity to BottomNavigationDrawerFragment and set the text of the passed variable to texview
Here is my pathetic attempt

MainActivity

override fun showCategory(str: String) {
        mCategory!!.text = str
        newInstance(str)
    }

fun newInstance(index: String): BottomNavigationDrawerFragment {
        val f = BottomNavigationDrawerFragment()
        // Supply index input as an argument.
        val args = Bundle()
        args.putString("index", index)
        f.arguments = args
        return f
    }

BottomNavigationDrawerFragment

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {

        var args = arguments
        textViewName.text = args!!.getString("index", "default") // Здесь возникает ошибка

        return inflater.inflate(R.layout.fragment_bottom_navigation_drawer, container, false)
    }

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
illuzor, 2018-09-23
@PainMain

You are accessing textViewName most likely through kotlin-android-extensions, the view does not yet exist in the onCreateView() method. You can either get it from the view that is inflated, or access it after calling onCreateView (), for example, in onActivityCreated ()

V
Vlad Kovalev, 2018-09-23
@zeekenru

val view = inflater.inflate(R.layout.fragment_bottom_navigation_drawer, container, false)
view.textViewName.text = args!!.getString("index", "default")

or
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        textViewName.text = arguments!!.getString("index", "default")
}

K
kristoft, 2018-09-24
@kristoft

Show the top lines of your `build.gradle`, layout and BottomNavigationDrawerFragment imports.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question