问题
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:
- Start iterating the view hierarchy to the top (i.e. call
v.getParent()
) until you reach the LinearLayout. - Call
findViewById
on the containing activity (or fragment's root view) instead of thev
object.
来源:https://stackoverflow.com/questions/29524453/android-java-langnullpointerexception-null-object-reference