adler jawad adler jawad - 1 year ago 71
Android Question

Android - How can I access a RelativeLayout instantiated in onCreateView() from an other method in a Fragment

i want when user click the back button the relativelayout disappears

In my onCreateView() method, I'm instantiating a RelativeLatout View:


public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_verbs,container, false);
relativeLayout = (RelativeLayout)rootView.findViewById(;

and i want to to access the relative from an other methode (backButtonWasPressed())

public void backButtonWasPressed() {
Log.d("hi ", "back is pressed");

if (!visible) {


} else relativeLayout.setVisibility(View.VISIBLE);

and this method is called in MainActivity2 when back button pressed:


public void onBackPressed() {

VerbFragment fragment = new VerbFragment();


but i get this error :

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.RelativeLayout.setVisibility(int)' on a null object reference
at Fragments.VerbFragment.backButtonWasPressed(
at Activitys.MainActivity2.onBackPressed(

Answer Source

When fragment was added to Activity, it has a tag argument.

fragmentTransaction.add(, fragment, tag);

Now, in your Activity's backButtonWasPressed() method, you can find that fragment using the tag and if it's not null , call backButtonWasPressed() of fragment.

FragmentManager fragmentManager = getSupportFragmentManager();
Fragment verbFragment = fragmentManager.findFragmentByTag(fragmentTag);
if(verbFragment !=null && verbFragment .isVisible()){
    verbFragment .backButtonWasPressed();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download