Android Viewpager with partial view on 4 fragments - android

I'm using viewpager and populating it with 4 fragments.
I cannot upload images to show what it looks like. However, I have uploaded the images to a picture hosting website and have included the link to the image here.
What I need is: http://postimg.org/image/3l4h53ucl/
However, what I can currently get to work is: http://postimg.org/image/m5kauitzr/
How can I fix this?
I have seen this being done perfectly on a viewpager with 3 pages:ViewPager - get a partial view of the next page
MainActivity.java Global Variables
PagerAdapter myPagerAdapter;
ViewPager myPager;
List<Fragment> myDefaultFragments;
MainActivity.java
myDefaultFragments = new Vector<Fragment>();
myDefaultFragments.add(Fragment.instantiate(this, SettingsFragment.class.getName()));
myDefaultFragments.add(Fragment.instantiate(this, MainFragment.class.getName()));
myDefaultFragments.add(Fragment.instantiate(this, FriendsFragment.class.getName()));
myDefaultFragments.add(Fragment.instantiate(this, MessagesFragment.class.getName()));
myPagerAdapter = new PagerAdapter(this.getSupportFragmentManager(), myDefaultFragments);
myPager = (ViewPager) findViewById(R.id.viewPager);
myPager.setAdapter(myPagerAdapter);
PagerAdapter.java
public class PagerAdapter extends FragmentPagerAdapter {
private List<Fragment> myFragments;
public PagerAdapter(FragmentManager fm, List<Fragment> fragments){
super(fm);
this.myFragments = fragments;
}
#Override
public Fragment getItem(int whichFrag){
return this.myFragments.get(whichFrag);
}
#Override
public int getCount(){
return this.myFragments.size();
}
#Override
public float getPageWidth(int position) {
if (position == 0 || position == 2){
return 0.9f;
} else if (position == 3) {
return 0.8f;
}
return 1f;
}
}

I don't know exactly what values you need to enter, but you should try some values and check what they do.
My guess:
Position 0: 0.9f
Position 1: 1.3f
Position 2: 1f
Position 3: 0.8f
I'm not sure what the ViewPager does for values larger than 1.0f, but it might work.

change:
#Override
public float getPageWidth(int position) {
if (position == 0 || position == 2){
return 0.9f;
} else if (position == 3) {
return 0.8f;
}
return 1f;
}
to:
#Override
public float getPageWidth(int position) {
switch(position){
case 0:
return 0.9f;
case 1:
return 1.2f;
case 2:
return 1f;
case 3:
return 0.9f;
default:
return 1f;
}
}

Related

Viewpager inside Viewpager Scroll Issue

in my main activity i have a horizontal viewpager. Inside one of the fragment of the viewpager i have another vertical viewpager. Both works fine. But for the horizontal viewpager, i need to scroll from the edge of the screens. But i want it to be scrolled from anywhere in the screen.
my horizontal viewpager setup:
viewPager = (ViewPager) findViewById(R.id.viewpager);
adapterViewPager = new HorizontalViewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapterViewPager);
viewPager.setCurrentItem(1);
horizontal viewpager adapter:
public class HorizontalViewPagerAdapter extends FragmentPagerAdapter {
private static int NUM_ITEMS = 3;
public HorizontalViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return MoreFragment.newInstance("Fragment MoreFragment", "HA HA HA");
case 1:
return NewsFragment.newInstance("Fragment 1", "HA HA HA");
case 2:
return WebViewFragment.newInstance("Fragment Webview", "HA HA HA");
default:
return null;
}
}
#Override
public int getCount() {
return NUM_ITEMS;
}
#Override
public CharSequence getPageTitle(int position) {
return "Tab " + position;
}
}
in my news fragment i have another viewpager.
viewPager = view.findViewById(R.id.shortpager);
adapterViewPager = new VerticalPagerAdapter(getActivity().getSupportFragmentManager(), newsList);
viewPager.setAdapter(adapterViewPager);
My vertical viewpager class:
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);
}
/**
* 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));
}
private class VerticalPageTransformer implements ViewPager.PageTransformer {
private static final float MIN_SCALE = 0.75f;
#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 <= 0) { // [-1,0]
// Use the default slide transition when moving to the left/top page
view.setAlpha(1);
ViewCompat.setElevation(view, 1);
// Counteract the default slide transition
view.setTranslationX(view.getWidth() * -position);
view.setTranslationY(0);
//set Y position to swipe in from top
float scaleFactor = MIN_SCALE + (1 - MIN_SCALE) * (1 - Math.abs(position));
view.setScaleX(scaleFactor);
view.setScaleY(scaleFactor);
} else if (position <= 1) { // [0,1]
view.setAlpha(1);
ViewCompat.setElevation(view, 2);
// Counteract the default slide transition
view.setTranslationX(view.getWidth() * -position);
view.setTranslationY(position * view.getHeight());
// Scale the page down (between MIN_SCALE and 1)
view.setScaleX(1);
view.setScaleY(1);
} else { // (1,+Infinity]
// This page is way off-screen to the right.
view.setAlpha(0);
}
}
}
}
vertical viewpager adapter:
public class VerticalPagerAdapter extends FragmentPagerAdapter {
private static int NUM_ITEMS = 3;
private final ArrayList<News> newsList;
public VerticalPagerAdapter(FragmentManager fm, ArrayList<News> newsList) {
super(fm);
this.newsList = newsList;
}
#Override
public Fragment getItem(int position) {
return ShortFragment.newInstance("Fragment 1", "HA HA HA", newsList.get(position));
}
#Override
public int getCount() {
return this.newsList.size();
}
#Override
public CharSequence getPageTitle(int position) {
return "Tab " + position;
}
}
Vertical viewpager scrolls smoothly. Currently for horizontal viewpager, i have to scroll from the edge of the screens. But i need to make it scrolled like the vertical one from anywhere in the screen.
Issue with your code is your VerticalViewPager
If you notice the code,
#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;
}
Step-1, Call super with swapped gesture.
Step-2, Perform actions on vertical view pager with current gesture.
And if you specifically see the comment, // return touch coordinates to original reference frame for any child views this clearly tells that gesture is first consumed by child.
So in your vertical view pager since you are swapping the gestures, it is consuming the Horizontal Gesture even before passing it to the parent. Thats why your horizontal view pager do not get the gesture.
If you are using Vertical View Pager with any conflicting gesture implementation like ScrollView, Lists, RecyclerView, ViewPager, etc. use the one as in the link below. It is deprecated but works with all Gesture Conflicting Views.
https://github.com/kaelaela/VerticalViewPager
I had this issue and I resolved it by wrapping the viewpager in a Scrollview
<ScrollView
android:id="#+id/nested_scroll"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/view_pager"
android:nestedScrollingEnabled="false"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</ScrollView>

How to set dynamic height to view pager child fragments in android?

I am having view pager with 4 different fragments. In this, 3 fragments only contains webview. All the fragments load different contents. I unable to set a height based on the loaded content. For that, I wrote a custom viewpager to measure height of viewpager. For the first viewpager fragment, height is calculated properly. But when navigate to second or third fragment, viewpager height is not calculated accurately. I don't know, what is the issue is in my code and what i need to change to calculate proper height for each fragment after navigate to that view pager page. Here is my view pager and pager adapter codes. Kindly help me.
Custom View pager:
public class CustomViewPager extends ViewPager {
public CustomViewPager (Context context) {
super(context);
}
public CustomViewPager (Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
boolean wrapHeight = MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST;
final View tab = getChildAt(0);
int width = getMeasuredWidth();
int tabHeight = tab.getMeasuredHeight();
if (wrapHeight) {
// Keep the current measured width.
widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
}
int fragmentHeight = measureFragment(((Fragment) getAdapter().instantiateItem(this, getCurrentItem())).getView());
heightMeasureSpec = MeasureSpec.makeMeasureSpec(tabHeight + fragmentHeight + (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, getResources().getDisplayMetrics()), MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
#Override
public void setOnPageChangeListener(OnPageChangeListener listener) {
requestLayout();
invalidate();
super.setOnPageChangeListener(listener);
}
#Override
public void addOnPageChangeListener(OnPageChangeListener listener) {
super.addOnPageChangeListener(listener);
}
public int measureFragment(View view) {
if (view == null)
return 0;
view.measure(0, 0);
return view.getMeasuredHeight();
}
}
PagerAdapter:
public class MerchantsCataAdapter extends FragmentPagerAdapter {
Context context;
Merchant merchant;
Fragment fragment;
private int mCurrentPosition = -1;
private String[] tabs = {"Home", "About Us","Promotions","Store Information"};
public MerchantsCataAdapter(FragmentManager fm, Context context,Merchant merchant) {
super(fm);
this.context = context;
this.merchant = merchant;
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
fragment= new HomeContentFragment().newInstance(merchant.getCompany_home_content(),merchant.getVideo_url());
break;
case 1:
fragment= new AboutusFragment().newInstance(merchant.getFull_description(),merchant.getVideo_url());
break;
case 2:
fragment= new AboutusFragment().newInstance(merchant.getCompany_promotions(),merchant.getVideo_url());
break;
case 3:
fragment= new FragmentStoreInformation().newInstance(merchant.getMerchantId(),merchant.getName());
break;
}
return fragment;
}
#Override
public int getCount() {
return tabs.length;
}
public String getTabView(int position) {
return tabs[position];
}
Finally, I find the answer. Place below property in Webview in xml. This will take webview height automatically based on the content.
android:scrollbarStyle="insideOverlay"

Page curl not working in Action bar tabs

I am referred the Harism page curl to implement it in Action bar
tabs.Because I thought this is the only thing should fulfill my requirement.
Below I am showing the output what I get it till now.
I need to add the pager curl in Viewpager.So that the action bar tabs
will swipe along with curl page.
Below I am posted the codes related to that.
MainActivity.java:
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
private CurlView mCurlView;
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
#SuppressWarnings("unused")
private Menu optionsMenu;
private MenuItem menuItem;
// Tab titles
private String[] tabs = { "Top Rated", "Games", "Movies" };
#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int index = 0;
if (getLastNonConfigurationInstance() != null) {
index = (Integer) getLastNonConfigurationInstance();
}
mCurlView = (CurlView) findViewById(R.id.curl);
mCurlView.setPageProvider(new PageProvider());
mCurlView.setSizeChangedObserver(new SizeChangedObserver());
mCurlView.setCurrentIndex(index);
mCurlView.setBackgroundColor(0xFF202830);
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME
| ActionBar.DISPLAY_SHOW_TITLE | ActionBar.DISPLAY_SHOW_CUSTOM);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onPause() {
super.onPause();
mCurlView.onPause();
}
#Override
public void onResume() {
super.onResume();
mCurlView.onResume();
}
#Override
public Object getLastCustomNonConfigurationInstance() {
return mCurlView.getCurrentIndex();
}
/**
* Bitmap provider.
*/
private class PageProvider implements CurlView.PageProvider {
// Bitmap resources.
private int[] mBitmapIds = { R.layout.fragment_top_rated, R.layout.fragment_games,
R.layout.fragment_movies };
#Override
public int getPageCount() {
return 2;
}
private Bitmap loadBitmap(int width, int height, int index) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Log.d("index", String.valueOf(index));
View v = inflater.inflate(mBitmapIds[index], null);
v.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(),
Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.draw(c);
return b;
}
#Override
public void updatePage(CurlPage page, int width, int height, int index) {
switch (index) {
// First case is image on front side, solid colored back.
default:
Bitmap front = loadBitmap(width, height, 0);
page.setTexture(front, CurlPage.SIDE_FRONT);
page.setColor(Color.rgb(180, 180, 180), CurlPage.SIDE_BACK);
break;
}
}
}
/**
* CurlView size changed observer.
*/
private class SizeChangedObserver implements CurlView.SizeChangedObserver {
#Override
public void onSizeChanged(int w, int h) {
if (w > h) {
mCurlView.setViewMode(CurlView.SHOW_TWO_PAGES);
mCurlView.setMargins(.1f, .05f, .1f, .05f);
} else {
mCurlView.setViewMode(CurlView.SHOW_ONE_PAGE);
// mCurlView.setMargins(.1f, .1f, .1f, .1f);
}
}
}
}
activity_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" >
<info.androidhive.tabsswipe.adapter.CurlView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/curl"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</info.androidhive.tabsswipe.adapter.CurlView>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</android.support.v4.view.ViewPager>
</LinearLayout>
TopRatedFragment.java:
public class TopRatedFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_top_rated, container, false);
return rootView;
}
}
fragment_top_rated.xml:
<?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"
android:background="#fa6a6a"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center"
android:text="Design Top Rated Screen"
android:textSize="20dp" />
</RelativeLayout>
TabsPagerAdapter.java:
import info.androidhive.tabsswipe.GamesFragment;
import info.androidhive.tabsswipe.MoviesFragment;
import info.androidhive.tabsswipe.TopRatedFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// Top Rated fragment activity
return new TopRatedFragment();
case 1:
// Games fragment activity
return new GamesFragment();
case 2:
// Movies fragment activity
return new MoviesFragment();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 3;
}
}
My issue is I need to add the page curl in ViewPager.So that I can do the swipe along with viewpager.I didn't know how to do that.But I am trying to get it.Any suggestion is mostly appreciated.Thank you.
ActionBar tabs are deprecated in 5.0
Perhaps a page transform that doesn't break for use with a viewpager.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mPager.setPageTransformer(true, new DepthPageTransformer());
}
public class DepthPageTransformer implements ViewPager.PageTransformer {
private static final String TAG="DepthTransformer";
private static float MIN_SCALE = 0.75f;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void transformPage(View view, float position) {
int pageWidth = view.getWidth();
Log.d(TAG, "VIew " + view + " Position: " + position);
if (position <= -1) { // [-Infinity,-1) ] ***
// RLP> I Changed to include "-1" as well: When position is -1, the view is not visible
// This page is way off-screen to the left.
view.setAlpha(0);
Log.d(TAG, "VIew "+view+" Position: "+position+", way left");
view.setVisibility(View.GONE);
} else if (position <= 0) { // [ (-1,0]
// Use the default slide transition when moving to the left page
view.setAlpha(1);
view.setTranslationX(0);
view.setScaleX(1);
view.setScaleY(1);
if (position==0) {
Log.d(TAG, "View "+view+" focused now?");
}
if (view.getVisibility()!=View.VISIBLE)
view.setVisibility(View.VISIBLE);
} else if (position <= 1) { // (0,1]
// Fade the page out.
view.setAlpha(1 - position);
// Counteract the default slide transition
// I THINK THIS IS WHAT BREAKS EVERYTHING
// ViewPager normally has the views one after another, but this makes all views on top
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);
if (position==1) {
Log.d(TAG, "View "+view+" invisible now?");
view.setVisibility(View.GONE);
// we totally hide the view. This seems to solve focus issue
} else {
if (view.getVisibility()!=View.VISIBLE)
view.setVisibility(View.VISIBLE);
}
} else { // (1,+Infinity]
// This page is way off-screen to the right.
view.setAlpha(0);
// we totally hide the view. This seems to solve focus issue
// I have to check for strange side-effects, but so far I found none :)
view.setVisibility(View.GONE);
Log.d(TAG, "VIew "+view+" Position: "+position+", way right");
}
}
}
Harism's page curl is designed for bitmaps, not for views. With that module, it is not possible to reach what you want, unless your tab contains only bitmaps

ViewPager animation fade in/out instead of slide

I got the FragmentBasics example from here. Is there a way make the ViewPager animation simply fade in and out when I swipe instead of sliding left and right? I've been trying some stuff with PageTransformer, but no success, I can still see it sliding. So I guess I need to somehow force its position to stay put, while sliding my finger only affects the alpha.
public class SecondActivity extends Activity {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setPageTransformer(false, new FadePageTransformer());
mViewPager.setAdapter(mSectionsPagerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.second, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
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;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
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";
/**
* Returns a new instance of this fragment for the given section number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_second, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
public class FadePageTransformer implements ViewPager.PageTransformer {
public void transformPage(View view, float position) {
if (position < -1 || position > 1) {
view.setAlpha(0);
}
else if (position <= 0 || position <= 1) {
// Calculate alpha. Position is decimal in [-1,0] or [0,1]
float alpha = (position <= 0) ? position + 1 : 1 - position;
view.setAlpha(alpha);
}
else if (position == 0) {
view.setAlpha(1);
}
}
}
This should work better for the fade in/out transform:
public void transformPage(View view, float position) {
view.setTranslationX(view.getWidth() * -position);
if(position <= -1.0F || position >= 1.0F) {
view.setAlpha(0.0F);
} else if( position == 0.0F ) {
view.setAlpha(1.0F);
} else {
// position is between -1.0F & 0.0F OR 0.0F & 1.0F
view.setAlpha(1.0F - Math.abs(position));
}
}
Based on a #murena's answer, this should work better for the fade in/out transform. At the end of animation the position is restored to default value.
public void transformPage(View view, float position) {
if(position <= -1.0F || position >= 1.0F) {
view.setTranslationX(view.getWidth() * position);
view.setAlpha(0.0F);
} else if( position == 0.0F ) {
view.setTranslationX(view.getWidth() * position);
view.setAlpha(1.0F);
} else {
// position is between -1.0F & 0.0F OR 0.0F & 1.0F
view.setTranslationX(view.getWidth() * -position);
view.setAlpha(1.0F - Math.abs(position));
}
}
Fade according to Google:
https://developer.android.com/training/animation/reveal-or-hide-view
viewPager.setPageTransformer(false, new ViewPager.PageTransformer() {
#Override
public void transformPage(#NonNull View page, float position) {
page.setAlpha(0f);
page.setVisibility(View.VISIBLE);
// Start Animation for a short period of time
page.animate()
.alpha(1f)
.setDuration(page.getResources().getInteger(android.R.integer.config_shortAnimTime));
}
});
A simple fading transformer could be implemented like this:
private static class FadePageTransformer implements ViewPager.PageTransformer {
public void transformPage(View view, float position) {
view.setAlpha(1 - Math.abs(position));
if (position < 0) {
view.setScrollX((int)((float)(view.getWidth()) * position));
} else if (position > 0) {
view.setScrollX(-(int) ((float) (view.getWidth()) * -position));
} else {
view.setScrollX(0);
}
}
}
Maybe not exactly what your looking for, but a good starting point.
I found #murena's answer super helpful. However, I ran into a problem when I tried to add an OnClickListener to each tab. I needed each page to open a different URL link. I modified the code to hide the views that are out of sight and added a little extra effect to slide the view at .5 the speed:
public void transformPage(View view, float position) {
if (position <= -1.0F || position >= 1.0F) { // [-Infinity,-1) OR (1,+Infinity]
view.setAlpha(0.0F);
view.setVisibility(View.GONE);
} else if( position == 0.0F ) { // [0]
view.setAlpha(1.0F);
view.setVisibility(View.VISIBLE);
} else {
// Position is between [-1,1]
view.setAlpha(1.0F - Math.abs(position));
view.setTranslationX(-position * (view.getWidth() / 2));
view.setVisibility(View.VISIBLE);
}
}

ViewPager - lastItem? Android

I've twenty images in my app.. I make use of ViewPager to show the previous/next images when the user swipes left/right in the app?? I would like to show "Repeat" screen when the user swipes to the right in the last image..
Here is my code,
viewPager = (ViewPager) findViewById(R.id.main_viewpager);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
PageListener pageListener = new PageListener();
viewPager.setOnPageChangeListener((OnPageChangeListener) pageListener);
int currentPage;
private class PageListener extends SimpleOnPageChangeListener{
public void onPageSelected(int position) {
--- some code -----
currentPage = position;
}
}
private class ImagePagerAdapter extends PagerAdapter {
#Override
public int getCount() {
return mImages.size();
}
-- other implemented methods ---
}
Is it possible to capture the event when the user swipes to the right of the last element in the viewpager??
You can achieve this by setting a custom onChangePageListener on your ViewPager like you started. I'd do it like:
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
//...
#Override
public void onPageSelected(int arg0) {
onPageChanged(arg0);
}
//...
});
And then in your activity
public void onPageChanged(int position) {
if(position == SOMETHING) //do something
}
Hope this helps
what you can do is grab an instance of the viewpager and call :
PagerAdapter pg = viewPager.getAdapter();
int i = pg.getCount();
this will return the count of pages in viewPager now what you can do is:
apply a condition to check your current page with the total count...
note that first page is [0] 2nd is [1] and 3rd is [2]...the current page's count is returned by...
viewPager.getCurrentItem()
Hope this solves your problem!
From this link:
You can extend ViewPager class and then override onTouchEvent() method:
Here for an example:
public class MxTViewPager extends ViewPager {
public MxTViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
float mStartDragX;
OnSwipeOutListener mListener;
public void setOnSwipeOutListener(OnSwipeOutListener listener) {
mListener = listener;
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
if (getCurrentItem() == getAdapter().getCount() - 1) {
final int action = ev.getAction();
float x = ev.getX();
switch (action & MotionEventCompat.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
mStartDragX = x;
break;
case MotionEvent.ACTION_UP:
if (x < mStartDragX) {
mListener.onSwipeOutAtEnd();
} else {
mStartDragX = 0;
}
break;
}
} else {
mStartDragX = 0;
}
return super.onTouchEvent(ev);
}
public interface OnSwipeOutListener {
public void onSwipeOutAtEnd();
}
}
Hope it can help you!

Categories

Resources