VideoView使用Viewpager开始以错误的片段播放

时间:2018-08-22 21:11:01

标签: android android-fragments android-viewpager

问题:我有一个包含3个片段的viewPager,第一个有videoView。当我切换到第二个片段时,视频停止播放,而当我切换到第三个片段时,视频保持不变。但是,当我从第三个片段更改为第二个片段时,视频开始在后台播放。 我希望视频仅在第一个片段中播放。我怎么解决这个问题?谢谢

这是我的代码:

活动适配器:

import android.net.Uri;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import android.widget.TextView;

public class ActivitySwipe extends AppCompatActivity implements 
HomeFragment.OnFragmentInteractionListener , 
CamaraFragment.OnFragmentInteractionListener
, SearchFragment.OnFragmentInteractionListener{

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link FragmentPagerAdapter} derivative, which will keep every
 * loaded fragment in memory. If this becomes too memory intensive, it
 * may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
private SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
private ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_swipe);

  /*  Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);*/
    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    final HomeFragment homeFragment = new HomeFragment();

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

   /* FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });*/
    mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        public void onPageScrollStateChanged(int state) {}
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }
        public void onPageSelected(int position) {
            // Check if this is the page you want.
        }
    });
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_activity_swipe, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
public void onFragmentInteraction(Uri uri) {

}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    public PlaceholderFragment() {
    }

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static Fragment newInstance(int sectionNumber) {

        Fragment fragment = null;

        switch (sectionNumber){

            case 1 : fragment=new HomeFragment();
            break;
            case 2 : fragment=new CamaraFragment();
                break;
            case 3 : fragment=new SearchFragment();
                break;
        }

        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_activity_swipe, container, false);
        TextView textView = (TextView) rootView.findViewById(R.id.section_label);
        textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
        return rootView;
    }
}

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        return PlaceholderFragment.newInstance(position + 1);
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 3;
    }
 }
}

这是我的第一个片段:

import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.VideoView;



/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link HomeFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link HomeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HomeFragment extends Fragment{
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
VideoView videoview;
MediaPlayer mediap;
int position;

    // TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;

private OnFragmentInteractionListener mListener;

public HomeFragment() {
    // Required empty public constructor
}

/**
 * Use this factory method to create a new instance of
 * this fragment using the provided parameters.
 *
 * @param param1 Parameter 1.
 * @param param2 Parameter 2.
 * @return A new instance of fragment HomeFragment.
 */
// TODO: Rename and change types and number of parameters
public static HomeFragment newInstance(String param1, String param2) {
    HomeFragment fragment = new HomeFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setUserVisibleHint(false);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
   View v= inflater.inflate(R.layout.fragment_home, container, false);

    videoview = (VideoView) v.findViewById(R.id.video1);

    videoview.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared( MediaPlayer mp) {
            mp.setLooping(true);
           mediap=mp;
        }
    });

    Uri uri = Uri.parse("android.resource://" +  getActivity().getPackageName() + "/" + R.raw.vid5);
    videoview.setVideoURI(uri);
    videoview.requestFocus();
    videoview.start();


    return v;
}


// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}

 @Override
 public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
        resume();
    }
    else {
        pause();
    }
}


@Override
public void setMenuVisibility(final boolean visible) {
    super.setMenuVisibility(visible);
    if (visible&&isResumed()) {
        resume();
    }else{
        pause();
    }
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof OnFragmentInteractionListener) {
        mListener = (OnFragmentInteractionListener) context;
    } else {
        throw new RuntimeException(context.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

public void pause(){
    //NOT videoview.pause(); Needn't save Stop position
    if (mediap != null){
        mediap.pause();
    }
}

public void resume(){
    //NOT videoview.resume();
    if (mediap != null){
        mediap.start(); //Video will begin where it stopped
    }
}


    @Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

/**
 * This interface must be implemented by activities that contain this
 * fragment to allow an interaction in this fragment to be communicated
 * to the activity and potentially other fragments contained in that
 * activity.
 * <p>
 * See the Android Training lesson <a href=
 * "http://developer.android.com/training/basics/fragments/communicating.html"
 * >Communicating with Other Fragments</a> for more information.
 */
public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    void onFragmentInteraction(Uri uri);
}
}

第二个片段:

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


/**
  * A simple {@link Fragment} subclass.
  * Activities that contain this fragment must implement the
  * {@link CamaraFragment.OnFragmentInteractionListener} interface
  * to handle interaction events.
  * Use the {@link CamaraFragment#newInstance} factory method to
  * create an instance of this fragment.
 */
public class CamaraFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;

private OnFragmentInteractionListener mListener;

public CamaraFragment() {
    // Required empty public constructor
}

/**
 * Use this factory method to create a new instance of
 * this fragment using the provided parameters.
 *
 * @param param1 Parameter 1.
 * @param param2 Parameter 2.
 * @return A new instance of fragment CamaraFragment.
 */
// TODO: Rename and change types and number of parameters
public static CamaraFragment newInstance(String param1, String param2) {
    CamaraFragment fragment = new CamaraFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_camara, container, false);
}

// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof OnFragmentInteractionListener) {
        mListener = (OnFragmentInteractionListener) context;
    } else {
        throw new RuntimeException(context.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

/**
 * This interface must be implemented by activities that contain this
 * fragment to allow an interaction in this fragment to be communicated
 * to the activity and potentially other fragments contained in that
 * activity.
 * <p>
 * See the Android Training lesson <a href=
 * "http://developer.android.com/training/basics/fragments/communicating.html"
 * >Communicating with Other Fragments</a> for more information.
 */
public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    void onFragmentInteraction(Uri uri);
}
}

3 个答案:

答案 0 :(得分:0)

使用FragmentPagerAdapter时,它将片段预先加载到焦点所在片段的左右。因此,当您从位置0滚动到1到2时,位置0的片段将被删除。然后,当您滚动回到位置1时,将重新加载位置0中的片段,这将触发创建视图。如果您看着自己的HomeFragment,则在OnCreateView()时会触发播放视频。

要解决此问题,您需要更改从创建片段时触发播放视频的方式,改为在滚动到视图中时激活它。空OnPageChangeListener已经到了一半。您应该检查onPageSelected()中的位置,然后在此处而不是片段的OnCreateView

中开始播放视频

答案 1 :(得分:0)

这是Android的一项功能,称为屏幕外页面限制,它将保留当前片段两侧的片段数量,默认值为1。当您从Tab3切换到Tab2时,将创建Tab1,但对于用户。仅使用setUserVisibleHint是不够的。这是解决方法。

HomeFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
   View v= inflater.inflate(R.layout.fragment_home, container, false);

    videoview = (VideoView) v.findViewById(R.id.video1);

    videoview.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared( MediaPlayer mp) {
            mp.setLooping(true);
           mediap=mp;
        }
    });

    Uri uri = Uri.parse("android.resource://" +  getActivity().getPackageName() + "/" + R.raw.vid5);
    videoview.setVideoURI(uri);
    videoview.requestFocus();

    if (getUserVisibleHint()) { // this fragment is visible
        videoview.start();
    }

    return v;
}

 public void resume(){
    //NOT videoview.resume();
    if (mediap != null) {
        Boolean isPaused = !mediap.isPlaying() && mediap.getCurrentPosition() > 1;
        if (isPaused) {
            mediap.start(); //Video will begin where it stopped
        } else {
            videoview.start();
        }
    }
}

答案 2 :(得分:0)

您必须在播放视频的片段中覆盖setUserVisibleHint方法。

公共无效setUserVisibleHint

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) 
       {       
        super.setUserVisibleHint(isVisibleToUser);                         
         if (this.isVisible())
         {               
            if (!isVisibleToUser)
            {  
                //pause or stop video
            } else {                               
                //play your video               
            }
        } 
      }