adler jawad adler jawad - 1 month ago 10
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:

VerbFragment

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


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

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

if (!visible) {

relativeLayout.setVisibility(View.GONE);

} else relativeLayout.setVisibility(View.VISIBLE);
}


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

MainActivity2

@Override
public void onBackPressed() {

VerbFragment fragment = new VerbFragment();
fragment.backButtonWasPressed();

}


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(VerbFragment.java:258)
at Activitys.MainActivity2.onBackPressed(MainActivity2.java:136)

Answer

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

fragmentTransaction.add(R.id.container, 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();
}
Comments