Search code examples
javaandroidandroid-fragmentsandroid-activity

How to find a view in activity by id from fragment


I have a imageview on activity that has onclick to show dialog for help, the content of the dialog is dependent on what the fragment is about. The problem is i want to hide the help imageview after a scpecific fragment but I can't findviewbyID this imageview from inside the fragment to setVisibility as it returns null object reference.

i've made a public static string for the content of the dialog to change from inside the fragment.

MainActivity.java

ivHelp = findViewById(R.id.ivHelp);

private void showDialog(String title, String message){
    if(title.equals("hide")){
        ivHelp.setVisibility(View.INVISIBLE);
    }
    else {
        Dialog dialog = new Dialog(MainActivity.this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        Window window = dialog.getWindow();
        window.setBackgroundDrawableResource(android.R.color.transparent);
        dialog.setContentView(R.layout.dialog_help);
        ImageView btnClose = (ImageView) dialog.findViewById(R.id.dialog_close);
        TextView tvTitle = (TextView) dialog.findViewById(R.id.dialog_title);
        TextView tvMessage = (TextView) dialog.findViewById(R.id.dialog_message);

        tvTitle.setText(title);
        tvMessage.setText(message);

        btnClose.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }
}

Fragment

fragmentview = inflater.inflate(R.layout.fragment_enter_car_details, container, false);

ivHelp = fragmentview.findViewById(R.id.ivHelp);
btnBook = fragmentview.findViewById(R.id.btnEnterCarDetails_Book);
btnBook.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ivHelp.performClick();
            MainActivity.dialogTitle="hide";
            FragmentTransaction ft =getActivity().getSupportFragmentManager().beginTransaction();
            ft.replace(R.id.content_frame, new FindingWasherFragment());
            ft.commit();
        }
    });

return fragmentview;

This is the activity

This is the fragment

The imageview is the question mark on the activity


Solution

  • i solved it by using this

    ivHelp = ((MainActivity)getContext()).findViewById(R.id.ivHelp);
    

    then the

    ivHelp.setVisibility(View.INVISIBLE);
    

    worked