I am having an issue with VideoView when using with VerticalViewPager.
When I scroll/swipe the ViewPager the VideoView becomes black. Actually here VideoView is getting disappeared the black color is the background of the ViewPager.
I don't have this issue when using horizontal ViewPager even with current custom VerticalViewpager set to horizontal.
When I scroll, VideoView disappears and when I lift my finger from screen VideoView appears back again.
I have tried many VerticalViewpager libraries and almost all of them have this same issue.
Have anyone faced this issue before? How to fix this?
These are the screenshots:
VideoView when not swiping:
VideoView when swiping vertically:
Here is my code
VerticalViewpager.java
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
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() {
// The majority of the magic happens here
setPageTransformer(true, new VerticalPageTransformer());
// The easiest way to get rid of the overscroll drawing that happens on the left and right
setOverScrollMode(OVER_SCROLL_NEVER);
}
private class VerticalPageTransformer implements ViewPager.PageTransformer {
#Override
public void transformPage(View view, float position) {
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(view.getWidth() * -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);
}
}
}
/**
* Swaps the X and Y coordinates of your touch event.
*/
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); // return touch coordinates to original reference frame for any child views
return intercepted;
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
return super.onTouchEvent(swapXY(ev));
}
}
MainActivity.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v7.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
MyPagerAdapter adapterViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
VerticalViewpager vpPager = (VerticalViewpager) findViewById(R.id.vpPAger);
adapterViewPager = new MyPagerAdapter(getSupportFragmentManager());
vpPager.setAdapter(adapterViewPager);
for (int i = 0; i < 2; i++) {
adapterViewPager.addFragment(FragmentWithOneImage.newInstance("Frag "+ i,R.drawable.jackie));
}
vpPager.setAdapter(adapterViewPager);
}
public static class MyPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment) {
mFragments.add(fragment);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public float getPageWidth(int position) {
return super.getPageWidth(position);
}
}
}
FragmentWithOneImage.java
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;
import android.widget.ImageView;
import android.widget.VideoView;
public class FragmentWithOneImage extends Fragment {
private String title;
private int image;
public static FragmentWithOneImage newInstance(String title, int resImage) {
FragmentWithOneImage fragment = new FragmentWithOneImage();
Bundle args = new Bundle();
args.putInt("image", resImage);
args.putString("title", title);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
image = getArguments().getInt("image", 0);
title = getArguments().getString("title");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one_img, container, false);
ImageView imageView = (ImageView) view.findViewById(R.id.imgMain);
imageView.setImageResource(image);
Uri uri = Uri.parse("http://abhiandroid-8fb4.kxcdn.com/ui/wp-content/uploads/2016/04/videoviewtestingvideo.mp4");
VideoView simpleVideoView = (VideoView) view.findViewById(R.id.simpleVideoView); // initiate a video view
simpleVideoView.setVideoURI(uri);
simpleVideoView.start();
return view;
}
#Override
public void onResume() {
super.onResume();
}
}
activiy_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.example.sudheeshm.verticalviewpager.VerticalViewpager
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/vpPAger"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:swipe_orientation="vertical"
android:background="#android:color/black"/>
</LinearLayout>
fragment_one_img.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
>
<VideoView
android:id="#+id/simpleVideoView"
android:layout_width="match_parent"
android:layout_height="300dp" />
<ImageView
android:layout_below="#+id/simpleVideoView"
android:id="#+id/imgMain"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="VerticalViewpager" >
<attr name="swipe_orientation" format="enum" >
<enum name="horizontal" value="0" />
<enum name="vertical" value="1" />
</attr>
</declare-styleable>
</resources>
It has to do with VideoView being based on SurfaceView and this view is not optimized for tranlations (scrolling in a ViewPager). Check out these answers related to VideoViews in a ViewPager at these following links: post 1, 2.
Maybe you can find a solution to your issue.
Related
I am very new to Android Development and for a project of mine I want to be able to have multiple animations for a fragment. The ones I want is to be able to swipe left and right and zoom in and out for each fragment. An example would be to have an Image in each fragment, and I could zoom in and out and swipe to the next image. I have seen examples online where this is achieved using a grid view. Is there any example or resources online where I can do this?
In my example I have here is that I used Viewpager 2 for the swipe animation then I attempted to implement a zoom-in feature but when I ran it overwrites the viewpager and I am unable to swipe pages only zoom in and out of that image. Can I somehow add the zoom feature in the PageTransformer class? I know this is probably a very poor way of going about it.
I know probably that in the in the PageTransformer class I need to add the zoom in and out animation how would I do that?
package com.example.viewpager;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.github.chrisbanes.photoview.PhotoView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setPageTransformer(true, new DepthPageTransformer());
viewPager.setAdapter(new MyPagerAdapter(this));
PhotoView photoView = (PhotoView) findViewById(R.id.photo_view);
photoView.setImageResource(R.drawable.a_child_of_the_king);
photoView.setImageResource(R.drawable.a_mighty_fortress);
photoView.setImageResource(R.drawable.a_quiet_place);
photoView.setImageResource(R.drawable.all_the_way);
}
//PageTranformer class
package com.example.viewpager;
import android.support.v4.view.ViewPager;
import android.view.View;
import com.github.chrisbanes.photoview.PhotoView;
//import androidx.viewpager.widget.ViewPager;
public class DepthPageTransformer implements ViewPager.PageTransformer {
private static final float MIN_SCALE = 0.75f;
public void transformPage(View view, float position) {
int pageWidth = view.getWidth();
if (position < -1) { // [-Infinity,-1)
// This page is way off-screen to the left.
view.setAlpha(0f);
} else if (position <= 0) { // [-1,0]
// Use the default slide transition when moving to the left page
view.setAlpha(1f);
view.setTranslationX(0f);
view.setScaleX(1f);
view.setScaleY(1f);
} else if (position <= 1) { // (0,1]
// Fade the page out.
view.setAlpha(1 - position);
// Counteract the default slide transition
view.setTranslationX(pageWidth * -position);
// Scale the page down (between MIN_SCALE and 1)
float scaleFactor = MIN_SCALE
+ (1 - MIN_SCALE) * (1 - Math.abs(position));
view.setScaleX(scaleFactor);
view.setScaleY(scaleFactor);
} else { // (1,+Infinity]
// This page is way off-screen to the right.
view.setAlpha(0f);
}
}
}
Swiping with Viewpager makes sense in a way.
Do you load all the images into the same Layout?
Are you inflating a Fragment and inflate the single Layout onto it and then load the image into the displayed ImageView?
If so, for zooming in and out you might have to modify this approach to register touches correctly:
private ScaleGestureDetector scaleGestureDetector;
private float mScaleFactor = 1.0f;
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView=findViewById(R.id.imageView);
scaleGestureDetector = new ScaleGestureDetector(this, new ScaleListener());
}
#Override
public boolean onTouchEvent(MotionEvent motionEvent) {
scaleGestureDetector.onTouchEvent(motionEvent);
return true;
}
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
#Override
public boolean onScale(ScaleGestureDetector scaleGestureDetector) {
mScaleFactor *= scaleGestureDetector.getScaleFactor();
mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 10.0f));
imageView.setScaleX(mScaleFactor);
imageView.setScaleY(mScaleFactor);
return true;
}
}
Happy Coding :)
Thanks, I am loading the images into the same layout. This is done in a separate class. see code below. Now The code that you provided am I able to just implement that to the Main Activity class? Would I be able to call:
viewPager.setPageTransformer(true, new DepthPageTransformer());
viewPager.setAdapter(new MyPagerAdapter(this)); as well as scaleGestureDetector function?
public class MyPagerAdapter extends PagerAdapter {
private Context mContext;
private int[] images = {
R.drawable.a_child_of_the_king,
R.drawable.a_mighty_fortress,
R.drawable.a_quiet_place,
R.drawable.all_the_way,
R.drawable.because_he_lives,
R.drawable.before_jehovahs_awful_throne,
R.drawable.before_jehovahs_awful_throne2,
R.drawable.beneath_the_cross_of_jesus
};
public MyPagerAdapter(Context context) {
mContext = context;
}
#Override
public Object instantiateItem(ViewGroup collection, int position) {
LayoutInflater inflater = LayoutInflater.from(mContext);
ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.imagelayout,
collection, false);
ImageView imageView = (ImageView)viewGroup.findViewById(R.id.imageView);
imageView.setImageResource(images[position]);
collection.addView(viewGroup);
return viewGroup;
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
((ViewGroup) collection).removeView((View) view);
}
#Override
public int getCount() {
return images.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public CharSequence getPageTitle(int position) {
ModelObject customPagerEnum = ModelObject.values()[position];
return mContext.getString(customPagerEnum.getTitleResId());
}
Want to create the view pager same as following UI, applied custom transformer but not working.
ViewPager.java
public class MyViewPager extends ViewPager implements ViewPager.PageTransformer {
public static final String TAG = "MyViewPager";
private float MAX_SCALE = 0.0f;
private int mPageMargin;
private boolean animationEnabled=true;
private boolean fadeEnabled=false;
private float fadeFactor=0.5f;
public MyViewPager(Context context) {
this(context, null);
}
public MyViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
// clipping should be off on the pager for its children so that they can scale out of bounds.
setClipChildren(false);
setClipToPadding(false);
// to avoid fade effect at the end of the page
setOverScrollMode(2);
setPageTransformer(false, this);
setOffscreenPageLimit(3);
mPageMargin = dp2px(context.getResources(), 50);
setPadding(mPageMargin, mPageMargin, mPageMargin, mPageMargin);
}
public int dp2px(Resources resource, int dp) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, resource.getDisplayMetrics());
}
public void setAnimationEnabled(boolean enable) {
this.animationEnabled = enable;
}
public void setFadeEnabled(boolean fadeEnabled) {
this.fadeEnabled = fadeEnabled;
}
public void setFadeFactor(float fadeFactor) {
this.fadeFactor = fadeFactor;
}
#Override
public void setPageMargin(int marginPixels) {
mPageMargin = marginPixels;
// setPadding(mPageMargin, mPageMargin, mPageMargin, mPageMargin);
}
#Override
public void transformPage(View page, float position) {
if (mPageMargin <= 0|| !animationEnabled)
return;
page.setPadding(mPageMargin / 3, mPageMargin / 3, mPageMargin / 3, mPageMargin / 3);
if (MAX_SCALE == 0.0f && position > 0.0f && position < 1.0f) {
MAX_SCALE = position;
}
position = position - MAX_SCALE;
float absolutePosition = Math.abs(position);
if (position <= -1.0f || position >= 1.0f) {
if(fadeEnabled)
page.setAlpha(fadeFactor);
// Page is not visible -- stop any running animations
} else if (position == 0.0f) {
// Page is selected -- reset any views if necessary
page.setScaleX((1 + MAX_SCALE));
page.setScaleY((1 + MAX_SCALE));
page.setAlpha(1);
} else {
page.setScaleX(1 + MAX_SCALE * (1 - absolutePosition));
page.setScaleY(1 + MAX_SCALE * (1 - absolutePosition));
if(fadeEnabled)
page.setAlpha( Math.max(fadeFactor, 1 - absolutePosition));
}
}
}
UPDATE - if you want to make current page zoom use below PageTransformer
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager2.widget.ViewPager2;
public class JavaActivity extends AppCompatActivity {
ViewPager2 myViewPager2;
MyAdapter MyAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_java);
myViewPager2 = findViewById(R.id.viewpager);
MyAdapter = new MyAdapter(this);
myViewPager2.setOrientation(ViewPager2.ORIENTATION_HORIZONTAL);
myViewPager2.setAdapter(MyAdapter);
myViewPager2.setOffscreenPageLimit(3);
float pageMargin = getResources().getDimensionPixelOffset(R.dimen.pageMargin);
float pageOffset = getResources().getDimensionPixelOffset(R.dimen.offset);
myViewPager2.setPageTransformer((page, position) -> {
float myOffset = position * -(2 * pageOffset + pageMargin);
if (position < -1) {
page.setTranslationX(-myOffset);
} else if (position <= 1) {
float scaleFactor = Math.max(0.7f, 1 - Math.abs(position - 0.14285715f));
page.setTranslationX(myOffset);
page.setScaleY(scaleFactor);
page.setAlpha(scaleFactor);
} else {
page.setAlpha(0);
page.setTranslationX(myOffset);
}
});
}
}
OUTPUT
NOTE: you can download complete code from my GitHub repositories
Try this way
JavaActivity
import android.os.Bundle;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.ViewCompat;
import androidx.viewpager2.widget.ViewPager2;
public class JavaActivity extends AppCompatActivity {
ViewPager2 myViewPager2;
MyAdapter MyAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_java);
myViewPager2 = findViewById(R.id.viewpager);
MyAdapter = new MyAdapter(this);
myViewPager2.setOrientation(ViewPager2.ORIENTATION_HORIZONTAL);
myViewPager2.setAdapter(MyAdapter);
myViewPager2.setOffscreenPageLimit(3);
float pageMargin= getResources().getDimensionPixelOffset(R.dimen.pageMargin);
float pageOffset = getResources().getDimensionPixelOffset(R.dimen.offset);
myViewPager2.setPageTransformer(new ViewPager2.PageTransformer() {
#Override
public void transformPage(#NonNull View page, float position) {
float myOffset = position * -(2 * pageOffset + pageMargin);
if (myViewPager2.getOrientation() == ViewPager2.ORIENTATION_HORIZONTAL) {
if (ViewCompat.getLayoutDirection(myViewPager2) == ViewCompat.LAYOUT_DIRECTION_RTL) {
page.setTranslationX(-myOffset);
} else {
page.setTranslationX(myOffset);
}
} else {
page.setTranslationY(myOffset);
}
}
});
}
}
activity_java layout file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".JavaActivity">
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/viewpager"
android:clipToPadding="false"
android:clipChildren="false"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
>
MyAdapter
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private Context context;
public MyAdapter(Context context) {
this.context = context;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.row_item, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.tvName.setText(String.format("Row number%d", position));
if (position % 2 ==0){
holder.imgBanner.setBackgroundColor(Color.RED);
}else {
holder.imgBanner.setBackgroundColor(Color.GREEN);
}
}
#Override
public int getItemCount() {
return 15;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView tvName;
ImageView imgBanner;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
tvName = itemView.findViewById(R.id.tvName);
imgBanner = itemView.findViewById(R.id.imgBanner);
}
}
}
row_item layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_marginLeft="#dimen/pageMarginAndOffset"
android:layout_marginRight="#dimen/pageMarginAndOffset"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/imgBanner"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorAccent"
android:contentDescription="#string/app_name"/>
<TextView
android:id="#+id/tvName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:layout_centerInParent="true"
android:textColor="#android:color/white"
android:textSize="20sp"
android:textStyle="bold"
tools:text="Hello"/>
</RelativeLayout>
OUTPUT
Using ViewPager2 (that has RecyclerView in it).
vp2 is instance of ViewPager2
This worked for me:
RecyclerView rv = (RecyclerView) vp2.getChildAt(0);
rv.setPadding(80, 0, 80, 0);
rv.setClipToPadding(false);
I used FragmentStateAdapter for it and overriding getItemId() and containsItem() for add/remove fragments.
result is here:
You can make use of clipToPadding and programmatically adding the pageMargin and padding to your viewpager.
Try something like this-
viewpager.setClipToPadding(false);
viewpager.setPadding(40, 0, 70, 0);
viewpager.setPageMargin(20);
I'm trying to figure out why my images within class CustomPagerAdapter mResources are NOT showing up once the VerticalViewPager widget appears -- nothing on start and nothing during vertical swipe.
I've been at it for a couple days but just cant crack it. Doesnt help the documentation on ViewPager / Adapters isnt very clear.
Using - Nexus 6 AVD, minSdkVersion = 19
When i attempt to scroll up (single click from the bottom and swipe up all the way to the top) i then receive this error message...
*AndroidRuntime: FATAL EXCEPTION: main
Process: sparktic.com.verticalviewpager, PID: 19242
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:3562)*
AFAIK i'm adding and removing pager_item correctly.
java/ MainActivity.java
package sparktic.com.verticalviewpager;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity
{
VerticalViewPager mPager;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPager = findViewById(R.id.viewpager);
CustomPagerAdapter adapter = new CustomPagerAdapter(this);
mPager.setAdapter(adapter);
}
class CustomPagerAdapter extends PagerAdapter
{
Context mContext;
public LayoutInflater mLayoutInflater;
int[] mResources = {
R.drawable.first, // Dload: https://i.imgur.com/suvAa9x.jpg
R.drawable.second, // Dload: https://i.imgur.com/c2f0Hvy.jpg
R.drawable.third // Dload: https://i.imgur.com/0GAs8qp.jpg
};
public CustomPagerAdapter(Context context)
{
mContext = context;
mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount()
{
return mResources.length;
}
#Override
public boolean isViewFromObject(View view, Object object)
{
return view == ((LinearLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position)
{
View itemView = mLayoutInflater.inflate(R.layout.pager_item, container, false);
ImageView imageView = (ImageView) itemView.findViewById(R.id.imageView);
imageView.setImageResource(mResources[position]);
container.addView(imageView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object)
{
container.removeView((LinearLayout) object);
}
}
}
layout/ activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="sparktic.com.verticalviewpager.MainActivity">
<sparktic.com.verticalviewpager.VerticalViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
layout/ pager_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/imageView" />
</LinearLayout>
java/ VerticalViewPager.java
package sparktic.com.verticalviewpager;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
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);
}
}
}
}
Solved my own problem. In case it helps someone else...
the issue was within "instantiateItem" method.
container.addView(imageView); should have been container.addView(itemView);
I still dont have a solid grasp as to what is happening within the PageAdapter overrides but it works so i'll take the win and move on.
I have a Custom ViewPager which act like a Carousel, the thing is I want to be able to show multiple page on one. To do so we have 2 solutions :
Using the margins setPageMargin() method
Or we can use Override the getPageWidth method of the adapter of my ViewPager.
The first solution is working great but I want to be able to precise exactly the percentage of my current page. The thing is with the getPageWidth solution my current page is shifting at the left. It's logical because she only takes 80% of her previous size. So I tried to override the scrollTo function of my custom ViewPager like this :
#Override
public void scrollTo(int x, int y) {
x = (int) (x - (getWidth() - getWidth()*getAdapter().getPageWidth(getCurrentItem()))/2);
super.scrollTo(x, y);
}
It's working but I can't scroll as before, it's just acting really weird, don't go in the good direction, don't follow the finger... Is there any solution which allow me to have a working scroll and a centered current page ?
Here is my adapter :
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 java.util.ArrayList;
public class CarouselAdapter extends FragmentPagerAdapter implements ViewPager.OnPageChangeListener {
private ArrayList<Entity> mData = new ArrayList<>();
private ScaledRelativeLayout cur = null, next = null;
private float scale;
private MainActivity context;
private FragmentManager fragmentManager;
public CarouselAdapter(MainActivity context, FragmentManager fragmentManager, ArrayList<Entity> mData) {
super(fragmentManager);
this.fragmentManager = fragmentManager;
this.context = context;
this.mData = mData;
}
#Override
public float getPageWidth(int position) {
return (0.85f);
}
#Override
public Fragment getItem(int position) {
if (position == MainActivity.FIRST_PAGE) {
scale = MainActivity.BIG_SCALE;
} else {
scale = MainActivity.SMALL_SCALE;
}
position = position % mData.size();
Fragment fragment = CarouselFragment.newInstance(context, mData.get(position), position, scale);
return fragment;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (positionOffset >= 0f && positionOffset <= 1f) {
cur = getRootView(position);
cur.setScaleBoth(MainActivity.BIG_SCALE - MainActivity.DIFF_SCALE * positionOffset);
if (position < mData.size()-1) {
next = getRootView(position +1);
next.setScaleBoth(MainActivity.SMALL_SCALE + MainActivity.DIFF_SCALE * positionOffset);
}
}
}
#Override
public void onPageSelected(int position) {}
#Override
public void onPageScrollStateChanged(int state) {}
private ScaledRelativeLayout getRootView(int position) {
return (ScaledRelativeLayout) fragmentManager.findFragmentByTag(this.getFragmentTag(position)).getView().findViewById(R.id.rootItem);
}
private String getFragmentTag(int position) {
return "android:switcher:" + context.carousel.getId() + ":" + position;
}
}
More useless but here is my MainActivity :
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import java.util.ArrayList;
public class MainActivity extends FragmentActivity {
public static int FIRST_PAGE;
public final static float BIG_SCALE = 1.0f;
public final static float SMALL_SCALE = 0.85f;
public final static float DIFF_SCALE = BIG_SCALE - SMALL_SCALE;
public CarouselViewPager carousel;
private CarouselAdapter carouselAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FIRST_PAGE = mData.size()/2;
carouselAdapter = new CarouselAdapter(this, this.getSupportFragmentManager(), mData);
carousel = (CarouselViewPager) findViewById(R.id.carousel);
carousel.setAdapter(carouselAdapter);
carousel.addOnPageChangeListener(carouselAdapter);
carousel.setCurrentItem(Math.round(FIRST_PAGE));
carousel.setOffscreenPageLimit(3);
carousel.setClipToPadding(false);
carousel.setScrollDurationFactor(2.5f);
}
}
Edit :
root.post(new Runnable() {
#Override
public void run() {
int width = root.getWidth();
Log.w("Post", "Width : " + width + ", newWidth : " + (width * 0.8));
// root.setPadding((int) (width * 0.125), 0, (int) (width * 0.125), 0);
ViewPager.LayoutParams params = (ViewPager.LayoutParams) root.getLayoutParams();
params.width = (int) (width * 0.8);
root.setLayoutParams(params);
root.requestLayout();
root.forceLayout();
root.invalidate();
}
});
Regards
Instead of setPageMargin or getPageWidth You can just set padding to your ViewPager.
<android.support.v4.view.ViewPager
android:id="#+id/main_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:clipToPadding="false" />
Notice the clipToPadding part, it is important to show other pages.
If you want to show your width as x% of the screen, you can do this in Java
mRootView.post(new Runnable() {
#Override
public void run() {
int w = mRootView.getWidth();
mViewPager.setPadding(w * 0.25, 0, w * 0.25, 0);
// 25% padding on either side so pages takes exactly 50% space
}
});
How can i implement same as the UI and code found in GitHub by using latest tools like ViewPager. the code founded hasn't developed with latest tools.It seems little difficult UI for me.
Any suggestion ?
Try like this
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.pagercontainer.PagerContainer
android:id="#+id/pager_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#CCC">
<android.support.v4.view.ViewPager
android:layout_width="150dp"
android:layout_height="100dp"
android:layout_gravity="center_horizontal" />
</com.example.pagercontainer.PagerContainer>
</RelativeLayout>
PagerActivity.java
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* PagerActivity: A Sample Activity for PagerContainer
*/
public class PagerActivity extends Activity {
PagerContainer mContainer;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mContainer = (PagerContainer) findViewById(R.id.pager_container);
ViewPager pager = mContainer.getViewPager();
PagerAdapter adapter = new MyPagerAdapter();
pager.setAdapter(adapter);
//Necessary or the pager will only have one extra page to show
// make this at least however many pages you can see
pager.setOffscreenPageLimit(adapter.getCount());
//A little space between pages
pager.setPageMargin(15);
//If hardware acceleration is enabled, you should also remove
// clipping on the pager for its children.
pager.setClipChildren(false);
}
//Nothing special about this adapter, just throwing up colored views for demo
private class MyPagerAdapter extends PagerAdapter {
#Override
public Object instantiateItem(ViewGroup container, int position) {
TextView view = new TextView(PagerActivity.this);
view.setText("Item "+position);
view.setGravity(Gravity.CENTER);
view.setBackgroundColor(Color.argb(255, position * 50, position * 10, position * 50));
container.addView(view);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View)object);
}
#Override
public int getCount() {
return 5;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return (view == object);
}
}
}
PagerContainer .java
import android.content.Context;
import android.graphics.Point;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.FrameLayout;
/**
* PagerContainer: A layout that displays a ViewPager with its children that are outside
* the typical pager bounds.
*/
public class PagerContainer extends FrameLayout implements ViewPager.OnPageChangeListener {
private ViewPager mPager;
boolean mNeedsRedraw = false;
public PagerContainer(Context context) {
super(context);
init();
}
public PagerContainer(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public PagerContainer(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
//Disable clipping of children so non-selected pages are visible
setClipChildren(false);
//Child clipping doesn't work with hardware acceleration in Android 3.x/4.x
//You need to set this value here if using hardware acceleration in an
// application targeted at these releases.
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
#Override
protected void onFinishInflate() {
try {
mPager = (ViewPager) getChildAt(0);
mPager.setOnPageChangeListener(this);
} catch (Exception e) {
throw new IllegalStateException("The root child of PagerContainer must be a ViewPager");
}
}
public ViewPager getViewPager() {
return mPager;
}
private Point mCenter = new Point();
private Point mInitialTouch = new Point();
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
mCenter.x = w / 2;
mCenter.y = h / 2;
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
//We capture any touches not already handled by the ViewPager
// to implement scrolling from a touch outside the pager bounds.
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
mInitialTouch.x = (int)ev.getX();
mInitialTouch.y = (int)ev.getY();
default:
ev.offsetLocation(mCenter.x - mInitialTouch.x, mCenter.y - mInitialTouch.y);
break;
}
return mPager.dispatchTouchEvent(ev);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//Force the container to redraw on scrolling.
//Without this the outer pages render initially and then stay static
if (mNeedsRedraw) invalidate();
}
#Override
public void onPageSelected(int position) { }
#Override
public void onPageScrollStateChanged(int state) {
mNeedsRedraw = (state != ViewPager.SCROLL_STATE_IDLE);
}
}
See this