Search code examples
javaandroidandroid-fragmentsandroid-imageviewandroid-toolbar

How to access image view of an activity from fragment?


I have an activity which has a toolbar, in that toolbar I have added one image view and have set the logo in it.

Also I have created different fragments, now when I see the fragment I want to hide that image view and set the title to the toolbar of an activity.

I have set the image view and toolbar as public static in home activity.

I tried to access toolbar like this:

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        View view = inflater.inflate(R.layout.fragment_account, container, false);

        final Toolbar toolbar = (Toolbar) ((HomeActivity) getActivity()).findViewById(R.id.toolbar);
        toolbar.setTitle(R.string.menu_account);
        ((HomeActivity) getActivity()).setSupportActionBar(toolbar);

       ((HomeActivity) getActivity()).mLogo.setVisibility(View.GONE);


        return view;
    }

But I am getting a null pointer on the image view and I can see the image on toolbar if commented setVisibility(View.GONE).

HomeActivity

public class HomeActivity extends AppCompatActivity{

    public static Toolbar toolbar;
    public static ImageView mLogo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        mLogo = (ImageView)findViewById(R.id.imageViewLogo);

        FragmentManager fragmentManager = HomeActivity.this.getFragmentManager();
        MainFragment fragment = new MainFragment();
        fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
        fragmentManager.beginTransaction().replace(R.id.mycontainer, fragment).commitAllowingStateLoss();

    }

}

Please help with this. Thank you.


Solution

  • Get Imageview from Activity like this

    ImageView mLogo = (ImageView)getActivity().findViewById(R.id.imageViewLogo);
    mLogo.setVisibility(View.GONE);