I've been doing some logic inside of a fragment's setUserVisibleHint()
method. I was always checking if isVisibleToUser
is true and then used getActivity
to return the activity. This was working well (100% of the time) until I updated the support library to the latest(support:appcompat-v7:24.2.0
). Now getActivity
always returns null. Are there some changes to the support library that explain this behaviour?
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(false);
if (isVisibleToUser) {
getActivity() <- null
}
I'm a bit late to the party but maybe this can help someone. I solved this problem by creating a boolean member inside the fragment class. I used this then to determine whether or not I was able to successfully get the activity in the setUserVisibleHint method. If not, I execute the activity-related code in onAttach. See below.
public MyFragment extends Fragment {
...
private boolean doInOnAttach = false;
@Override
public void setUserVisibleHint(boolean visible) {
super.setUserVisibleHint(visible);
// if the fragment is visible
if (true == visible) {
// ... but the activity has not yet been initialized
doInOnAttach = true;
} else {
myAction();
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (true == doInOnAttach) {
myAction();
doInOnAttach = false;
}
}
private void myAction() {
// code to execute here
}
}
Below Worked for me....
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
//// create class member variable to store view
viewFrag =inflater.inflate(R.layout.fragment_main_favorite, container, false);
// Inflate the layout for this fragment
return viewFrag;
}
and use this
@Override
public void setUserVisibleHint(boolean visible)
{
super.setUserVisibleHint(visible);
if (visible)
{
View v = viewFrag ;
if (v == null) {
Toast.makeText(getActivity(), "ERROR ", Toast.LENGTH_LONG ).show();
return;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With