I was able to find the solution to the problem "how to check if a fragment becomes visible in viewpager". But, I also want my gauge to animate everytime the fragment comes on the screen. However, it returns null pointer exception. I have used the isVisibleToUser method and the onResume() method. How can I solve this?
public class HumidityFragment extends Fragment {
View view;
public Boolean mIsVisibleToUser;
Gauge gauge;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_soil_moisture, container, false);
gauge = view.findViewById(R.id.gauge);
onVisible();
return view;
}
@Override
public void onStart () {
super.onStart();
if (mIsVisibleToUser) {
onVisible();
}
}
@Override
public void onResume() {
super.onResume();
onVisible();
}
@Override
public void onStop () {
super.onStop();
if (mIsVisibleToUser) {
onInVisible();
}
}
@Override
public void setUserVisibleHint ( boolean isVisibleToUser){
super.setUserVisibleHint(isVisibleToUser);
mIsVisibleToUser = isVisibleToUser;
if (isResumed()) { // fragment have created
if (mIsVisibleToUser) {
onVisible();
} else {
onInVisible();
}
}
}
public void onVisible () {
Toast.makeText(getContext(), "visible", Toast.LENGTH_SHORT).show();
gauge.moveToValue(78);
}
public void onInVisible () {
Toast.makeText(getActivity(), "invisible", Toast.LENGTH_SHORT).show();
}
}
You did not initialize the variable just give the default value to your variable
public Boolean mIsVisibleToUser = false;