How to call in Fragment a component and its Activity properties?

Asked

Viewed 140 times

1

I needed that when I entered the Fragment he executed this method Verifcar() in main Activity to check the condition and not show the RecyclerView.

Mainactivity.Java

public void Verificar(){
            if(pref.getBoolean(Constants.IS_LOGGED_IN,false)){

                recyclerView.setVisibility (View.VISIBLE);
    }else {

                recyclerView.setVisibility (View.INVISIBLE);
    }

}

1 answer

0


You can call your Activity method from within Fragment using:

((SuaActivity)getActivity()).seuMetodoPublico();

If you have problems with cast of Activity, you can use:

Activity activity = getActivity();

if (activity instanceof SuaActivity){
 ((SuaActivity) activity).seuMetodoPublico();
} 
  • Thank you for your suggestion, but I would like you to call this method by being called the Fragment in this case where I should place the method in the body of the Fragment ?

  • I recommend a override in your Fragment’s onActivityCreated() method. So it would only be called after the Views initialization.

  • Boy You’re a Genius, Success and thank you so much.

  • If the answer served you, please mark it as the correct answer so that others know that this solution served. Success for you too

Browser other questions tagged

You are not signed in. Login or sign up in order to post.