How to access parent Activity View in Fragment

落花浮王杯 提交于 2020-08-20 18:26:42

问题


I have an ActionBarActivity and fragment. I am using FragmentPagerAdapter that provides fragment to my app. My question How can I access parent Activity View in Fragment ??


回答1:


You can use

View view = getActivity().findViewById(R.id.viewid);

Quoting docs

Specifically, the fragment can access the Activity instance with getActivity() and easily perform tasks such as find a view in the activity layout




回答2:


At first, create a view like this:

View view = getActivity().findViewById(R.id.viewid);

Then convert it to any view that you need like this:

 if( view instanceof EditText ) {
            editText = (EditText) view;
            editText.setText("edittext");
            //Do your stuff
        }

or

if( view instanceof TextView ) {
  TextView textView = (TextView) view;
  //Do your stuff
}



回答3:


In Kotlin it is very easy to access parent Activity View in Fragment

activity!!.textview.setText("String")



回答4:


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<TextView>(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")
    }
}


来源:https://stackoverflow.com/questions/22883599/how-to-access-parent-activity-view-in-fragment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!