How to access parent Activity View in Fragment

AndroidAndroid FragmentsFragment

Android Problem Overview


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 ??

Android Solutions


Solution 1 - Android

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

Solution 2 - Android

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

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

Solution 3 - Android

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
}

Solution 4 - Android

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

Solution 5 - Android

if you are using kotlin then you can use this syntax

val view= requireActivity().findViewById<YourVIEW>(R.id.view_id)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBotView Question on Stackoverflow
Solution 1 - AndroidRaghunandanView Answer on Stackoverflow
Solution 2 - Androidkishan vermaView Answer on Stackoverflow
Solution 3 - AndroidMohsen mokhtariView Answer on Stackoverflow
Solution 4 - AndroidIrfandi D. VendyView Answer on Stackoverflow
Solution 5 - AndroidYazdan IlyasView Answer on Stackoverflow