android java.langNullPointerException null object reference

不打扰是莪最后的温柔 提交于 2019-12-24 07:45:53

问题


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);

                }


            };

回答1:


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.


来源:https://stackoverflow.com/questions/29524453/android-java-langnullpointerexception-null-object-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!