I have multiple buttons in my app and I would like to have a single click listener for all buttons in R.layout.fragment_general
. This is what I have tried:
View view = inflater.inflate(R.layout.fragment_general, container, false);
@SuppressLint("ResourceType") ViewGroup group = (ViewGroup) view.findViewById(R.layout.fragment_general);
View v;
for(int i = 0; i < group.getChildCount(); i++) {
v = group.getChildAt(i);
if(v instanceof Button) {
v.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
System.out.println("A button has been clicked");
}
});
}
}
My app will crash and I get the error:
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.ViewGroup.getChildCount()' on a null object reference
How should it be done correctly?
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.ViewGroup.getChildCount()' on a null object reference
It means, that your group
is null. That happened brcause of this
@SuppressLint("ResourceType") ViewGroup group = (ViewGroup) view.findViewById(R.layout.fragment_general);
You should write yours ViewGroups id in findViewbyId(), but not the fragments layout name.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.