0

I am trying to initialize all the navigation bar buttons and assign Black background color, when user clicks on one of the button, that one should change color and all other should remain Black. But i get the following error:

Attempt to invoke virtual method 'android.view.View android.widget.LinearLayout.getChildAt(int)' on a null object reference

    public void bottomNavIcons(View view){
            for(int i=0;i<Constants.bottom_nav_icon.length;i++) {

                LinearLayout linearLayout = (LinearLayout) view.findViewById(R.id.bottom_nav_bar);
                ImageButton imageButton = new ImageButton(getActivity());
                imageButton.setClickable(true);
                imageButton.setOnClickListener(onClickListener);
                imageButton.setImageResource(Constants.bottom_nav_icon[i]);
                imageButton.setBackgroundColor(Color.BLACK);
                imageButton.setPadding(70, 0, 70, 0);
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                linearLayout.addView(imageButton, layoutParams);

            }

        }
        View.OnClickListener onClickListener = new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    LinearLayout linearLayout = (LinearLayout) v.findViewById(R.id.bottom_nav_bar);
for(int i=0;i<Constants.bottom_nav_icon.length;i++) {
                    ImageView imageButton = (ImageView) linearLayout.getChildAt(i);
                    imageButton.setBackgroundColor(Color.BLACK);
        }
                    v.setBackgroundColor(Color.BLUE);

                }


            };
Vaibhav Desai
  • 2,334
  • 2
  • 25
  • 29

1 Answers1

3

I think this is the problem:

LinearLayout linearLayout = (LinearLayout) v.findViewById(R.id.bottom_nav_bar);

You are assuming the LinearLayout is inside the view which is clicked - my best guess is this is not true (you probably want to get the clicked view's parent, not child). You have 2 options:

  1. Start iterating the view hierarchy to the top (i.e. call v.getParent()) until you reach the LinearLayout.
  2. Call findViewById on the containing activity (or fragment's root view) instead of the v object.
Samuil Yanovski
  • 2,837
  • 17
  • 19