简体   繁体   中英

How do I only load one tab into memory at a time in Android?

I'm creating an application with a CustomPagerAdapter that can be controlled by ActionBar tabs or horizontal swipe. When you select a tab, a fragment corresponding to that tab is displayed on the screen. When the app is created and when any tab is selected, the adjacent tabs, fragments are loaded into memory. I do not want this to happen. I would like it so that when a tab is selected only that selected tab's fragment is loaded into memory. Is there a way to do this?

Edit: The code I'm currently having trouble with is as follows:

public class fragA extende Fragment
{
    private VideoView videoViewA;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View rootView = inflater.inflate(R.layout.fragment_A, container, false);

        videoViewA = (VideoView) rootView.findViewById(R.id.videoViewA);

        return rootView;
    }

    @Override
    public void setUserVisibleHint(final boolean isVisibleToUser)
    {
        super.setUserVisibleHint(isVisibleToUser)
        if (isVisibleToUser)
        {
            videoViewA.setVideoURI(LINK);
            videoViewA.start();
        }
        else
        {
            videoViewA.stopPlayback();
        }
    }
}

The error I'm receiving is at the videoViewA.setVideoURI(LINK); line. Mind you, the link is actually there, but for privacy reasons I cannot post it.

Edit 2: It's ajava.lang.NullPointerException.

Edit 3: Sorry, but I'm doing this all the hard way. The code now reflects what I have actually written.

Try loading your videos within setUserVisbleHint(), which gets fired by the FragmentPageAdapter upon showing the fragment. http://developer.android.com/reference/android/support/v4/app/Fragment.html#setUserVisibleHint(boolean)

If that doesn't work for you, you can also try to do check onHiddenChanged(boolean hidden). http://developer.android.com/reference/android/app/Fragment.html#onHiddenChanged(boolean)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM