如何使用ViewPager一次垂直滚动一项

时间:2018-06-23 13:54:27

标签: java android android-viewpager android-mediaplayer android-adapter

我想进行垂直滚动(一次滚动一次),但是找不到它们在我的代码上实现viewpager的方法。谁能帮助我在我的代码上实现视图分页器。我尝试使用Fragment获取垂直滚动,但没有运气。任何帮助将不胜感激。预先感谢。

这是我的代码,

MainActivity-

public class MainActivity extends AppCompatActivity {

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

    recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
    seekBar = (SeekBar) findViewById(R.id.seekBar);
    songAdapter = new SongAdapter(this, _songs);
    recyclerView.setAdapter(songAdapter);
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
    DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),
            linearLayoutManager.getOrientation());
    recyclerView.setLayoutManager(linearLayoutManager);
    recyclerView.addItemDecoration(dividerItemDecoration);
    songAdapter.setOnItemClickListener(new SongAdapter.OnItemClickListener() {
        @Override
        public void onItemClick(final Button b, View view, final SongInfo obj, int position) {
            if (b.getText().equals("Stop")) {
                mediaPlayer.stop();
                mediaPlayer.reset();
                mediaPlayer.release();
                mediaPlayer = null;
                b.setText("Play");
            } else {

                Runnable runnable = new Runnable() {
                    @Override
                    public void run() {
                        try {
                            mediaPlayer = new MediaPlayer();
                            mediaPlayer.setDataSource(obj.getSongUrl());
                            mediaPlayer.prepareAsync();
                            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                                @Override
                                public void onPrepared(MediaPlayer mp) {
                                    mp.start();
                                    seekBar.setProgress(0);
                                    seekBar.setMax(mediaPlayer.getDuration());
                                    Log.d("Prog", "run: " + mediaPlayer.getDuration());
                                }
                            });
                            b.setText("Stop");


                        } catch (Exception e) {
                        }
                    }

                };
                myHandler.postDelayed(runnable, 100);

            }
        }
    });
    checkUserPermission();

    Thread t = new runThread();
    t.start();
}

public class runThread extends Thread {


    @Override
    public void run() {
        while (true) {

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Log.d("Runwa", "run: " + 1);
            if (mediaPlayer != null) {
                seekBar.post(new Runnable() {
                    @Override
                    public void run() {
                        seekBar.setProgress(mediaPlayer.getCurrentPosition());
                    }
                });

                Log.d("Runwa", "run: " + mediaPlayer.getCurrentPosition());
            }
        }
    }

}

private void checkUserPermission() {
    if (Build.VERSION.SDK_INT >= 23) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 123);
            return;
        }
    }
    //getMp3Songs();
    loadSongs();
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
        case 123:
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //getMp3Songs();
                loadSongs();
            } else {
                Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
                checkUserPermission();
            }
            break;
        default:
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }

}

private void loadSongs() {
    Uri uri = MediaStore.Audio.Media.INTERNAL_CONTENT_URI;
   // Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;

    String selection = MediaStore.Audio.Media.IS_MUSIC + "!=0";
    Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
    if (cursor != null) {
        if (cursor.moveToFirst()) {
            do {
                String name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
                String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
                String url = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));

                Log.i("DATA111", url);

                mediaMetadataRetrieve = new MediaMetadataRetriever();
                mediaMetadataRetrieve.setDataSource(url);

                art = mediaMetadataRetrieve.getEmbeddedPicture();

                if (art != null) {
                    songImage = BitmapFactory.decodeByteArray(art, 0, art.length);
                }

                SongInfo s = new SongInfo(name, artist, url, songImage);
                _songs.add(s);

            } while (cursor.moveToNext());
        }

        cursor.close();
        songAdapter = new SongAdapter(MainActivity.this, _songs);

    }
}
}

SongAdapter-

private ArrayList<SongInfo> _songs = new ArrayList<SongInfo>();
private Context context;
private OnItemClickListener mOnItemClickListener;

public SongAdapter(Context context, ArrayList<SongInfo> songs) {
    this.context = context;
    this._songs = songs;
}

public interface OnItemClickListener {
    void onItemClick(Button b, View view, SongInfo obj, int position);
}

public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
    this.mOnItemClickListener = mItemClickListener;
}


@Override
public SongHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View myView = LayoutInflater.from(context).inflate(R.layout.row_songs, viewGroup, false);
    return new SongHolder(myView);
}

@Override
public void onBindViewHolder(final SongHolder songHolder, final int i) {
    final SongInfo s = _songs.get(i);
    songHolder.tvSongName.setText(_songs.get(i).getSongname());
    songHolder.tvSongArtist.setText(_songs.get(i).getArtistname());
    songHolder.tvAlbum_art.setImageBitmap(_songs.get(i).getThaImage());
    songHolder.btnAction.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mOnItemClickListener != null) {
                mOnItemClickListener.onItemClick(songHolder.btnAction, v, s, i);
            }
        }
    });
}

@Override
public int getItemCount() {
    return _songs.size();
}

public class SongHolder extends RecyclerView.ViewHolder {
    TextView tvSongName, tvSongArtist;
    Button btnAction;
    ImageView tvAlbum_art;

    public SongHolder(View itemView) {
        super(itemView);
        tvSongName = (TextView) itemView.findViewById(R.id.tvSongName);
        tvSongArtist = (TextView) itemView.findViewById(R.id.tvArtistName);
        tvAlbum_art = (ImageView) itemView.findViewById(R.id.album_art);
        btnAction = (Button) itemView.findViewById(R.id.button_action);
    }
}
}

VerticalViewPager-

public class VerticalViewPager extends ViewPager {

public VerticalViewPager(Context context) {
    this(context, null);
}

public VerticalViewPager(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
}

@Override
public boolean canScrollHorizontally(int direction) {
    return false;
}

@Override
public boolean canScrollVertically(int direction) {
    return super.canScrollHorizontally(direction);
}

private void init() {
    setPageTransformer(true, new VerticalPageTransformer());
    setOverScrollMode(View.OVER_SCROLL_NEVER);
}

@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
    final boolean toIntercept = super.onInterceptTouchEvent(flipXY(ev));
    flipXY(ev);
    return toIntercept;
}

@Override
public boolean onTouchEvent(MotionEvent ev) {
    final boolean toHandle = super.onTouchEvent(flipXY(ev));
    flipXY(ev);
    return toHandle;
}

private MotionEvent flipXY(MotionEvent ev) {
    final float width = getWidth();
    final float height = getHeight();
    final float x = (ev.getY() / height) * width;
    final float y = (ev.getX() / width) * height;
    ev.setLocation(x, y);
    return ev;
}

private static final class VerticalPageTransformer implements ViewPager.PageTransformer {
    @Override
    public void transformPage(View view, float position) {
        final int pageWidth = view.getWidth();
        final int pageHeight = view.getHeight();
        if (position < -1) {
            view.setAlpha(0);
        } else if (position <= 1) {
            view.setAlpha(1);
            view.setTranslationX(pageWidth * -position);
            float yPosition = position * pageHeight;
            view.setTranslationY(yPosition);
        } else {
            view.setAlpha(0);
        }
    }
}
}

2 个答案:

答案 0 :(得分:0)

简单的解决方案是尝试旋转viewpager及其子视图

mViewPager.setRotation(90);

它将旋转视图分页器以及子视图。现在再次以相反方向旋转子视图。

childView.setRotation(270);

答案 1 :(得分:0)

从这个简单的例子开始:

1)MnnnnnActivity.class:----------

public class MnnnnnActivity extends AppCompatActivity {


private VerticalViewPager vp;
private MPagerAdapter mPagerAdapter;
private int lastPage = 0;
private List<String> songs = new ArrayList<String>();

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

    vp = (VerticalViewPager) findViewById(R.id.vp);

    for(int i = 0 ; i<10  ; i++){
        songs.add(i , "song " + i);
    }

    mPagerAdapter = new MPagerAdapter(getApplicationContext(), songs);
    vp.setAdapter(mPagerAdapter);
    vp.setOffscreenPageLimit(1);

    vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            if(lastPage > position){ //left

            }else{ // right

            }
            lastPage = position;
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

}

}

2)MPagerAdapter.class:-----

public class MPagerAdapter extends PagerAdapter {

private Context mContext;
private List<String> songs = new ArrayList<String>();

public MPagerAdapter(Context context , List<String> songs) {
    mContext = context;
    this.songs = songs;
}

@Override
@NonNull
public Object instantiateItem(@NonNull final ViewGroup collection, final int position) {
    LayoutInflater inflater = LayoutInflater.from(mContext);
    View layout = (View) inflater.inflate(R.layout.layout_list, collection, false);

    TextView tv = (TextView) layout.findViewById(R.id.tv_song);
    tv.setText(songs.get(position));
    Button b = (Button) layout.findViewById(R.id.b_song);
    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(mContext , "Play " + songs.get(position) , Toast.LENGTH_LONG).show();
        }
    });
    collection.addView(layout);
    return layout;
}

@Override
public void destroyItem(ViewGroup collection, int position, Object view) {
    collection.removeView((View) view);
}

@Override
public int getCount() {
    return songs.size();
}

@Override
public boolean isViewFromObject(View view, Object object) {
    return view == object;
}

@Override
public CharSequence getPageTitle(int position) {
    return songs.get(position);
}

}

3)VerticalViewPager.class:-------

//https://stackoverflow.com/questions/13477820/android-vertical-viewpager

public class VerticalViewPager extends ViewPager {

public VerticalViewPager(Context context) {
    super(context);
    init();
}

public VerticalViewPager(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
}

private void init() {
    setPageTransformer(true, new VerticalPageTransformer());
    setOverScrollMode(OVER_SCROLL_NEVER);
}

private MotionEvent swapXY(MotionEvent ev) {
    float width = getWidth();
    float height = getHeight();

    float newX = (ev.getY() / height) * width;
    float newY = (ev.getX() / width) * height;

    ev.setLocation(newX, newY);
    return ev;
}

@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
    boolean intercepted = super.onInterceptTouchEvent(swapXY(ev));
    swapXY(ev);
    //https://stackoverflow.com/questions/15365915/viewpager-nested-in-viewpager
    int action = ev.getAction();
    switch (action) {
        case MotionEvent.ACTION_UP:
            this.getParent().requestDisallowInterceptTouchEvent(true);
            break;
        case MotionEvent.ACTION_DOWN:
            this.getParent().requestDisallowInterceptTouchEvent(true);
            break;
        case MotionEvent.ACTION_MOVE:
            this.getParent().requestDisallowInterceptTouchEvent(true);
            break;
    }
    return intercepted;
}

@Override
public boolean onTouchEvent(MotionEvent ev) {
    return super.onTouchEvent(swapXY(ev));
}

}

4)VerticalPageTransformer.class:-----------

//https://stackoverflow.com/questions/13477820/android-vertical-viewpager

public class VerticalPageTransformer implements ViewPager.PageTransformer {

@Override
public void transformPage(View view, float position) {
    int pageWidth = view.getWidth();
    int pageHeight = view.getHeight();

    if (position < -1) { // [-Infinity,-1)
        // This page is way off-screen to the left.
        view.setAlpha(0);

    } else if (position <= 1) { // [-1,1]

        view.setAlpha(1);

        // Counteract the default slide transition
        view.setTranslationX(pageWidth * -position);

        //set Y position to swipe in from top
        float yPosition = position * view.getHeight();
        view.setTranslationY(yPosition);

    } else { // (1,+Infinity]
        // This page is way off-screen to the right.
        view.setAlpha(0);
    }
}
}

5)layout5.xml:--------

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<com.example.admin.accessories.VerticalViewPager
android:id="@+id/vp"
android:layout_width="match_parent"
android:layout_height="match_parent">
</com.example.admin.accessories.VerticalViewPager>


</android.support.constraint.ConstraintLayout>

6)layout_list.xml:--------

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginTop="20dp"
    android:text="SName"
    android:layout_marginBottom="20dp"
    android:id="@+id/tv_song"/>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:text="Play"
    android:id="@+id/b_song"/>


</LinearLayout>

7)输出:---------

Output