How to access parent Activity View in Fragment

前端 未结 4 1076
刺人心
刺人心 2021-01-31 06:58

I have an ActionBarActivity and fragment. I am using FragmentPagerAdapter that provides fragment to my app. My question How can I access parent Activit

4条回答
  •  终归单人心
    2021-01-31 07:57

    Note that if you are using findViewById<>() from activity, it wont work if you call it from fragment. You need to assign the view to variable. Here is my case

    This doesn't work

    class MainActivity{
    
        fun onCreate(...){
            //works
            setMyText("Set from mainActivity")
        }
    
        fun setMyText(s: String){
            findViewById(R.id.myText).text = s
        }
    }
    ________________________________________________________________
    
    class ProfileFragment{
        ...
    
        fun fetchData(){
            // doesn't work
            (activity as MainActivity).setMyText("Set from profileFragment")
        }
    }
    

    This works

    class MainActivity{
    
        private lateinit var myText: TextView
    
        fun onCreate(...){
            myText = findViewById(R.id.myText)
    
            // works
            setMyText("Set from mainActivity")
        }
    
        fun setMyText(s: String){
            myText.text = s
        }
    }
    ________________________________________________________________
    
    class ProfileFragment{
        ...
    
        fun fetchData(){
            // works
            (activity as MainActivity).setMyText("Set from profileFragment")
        }
    }
    

提交回复
热议问题