ViewPager animation fade in/out instead of slide - android

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);
}
}

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 show Admob Interstitial ad after 5 swipes in vertical viewpager?

I have made an app in which I have added functionality of vertical swipe using ViewPager class. Now I need help to show Admob Interstitial ad after 5 swipes. I have seen several other SO question but could not get clarity.
Can anyone help me how can I do this? Here is my code:
MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mains);
mData = dbHelper.getAll(Data.class);
DATA_CARDS = mData.size();
ScreenSlidePagerAdapter screenSlidePagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
VerticalViewPager verticalViewPager = (VerticalViewPager) findViewById(R.id.pager);
verticalViewPager.setAdapter(screenSlidePagerAdapter);
}
ScreenSlidePagerAdapter
public class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
private static final int NUM_PAGES = MainActivity.DATA_CARDS;
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
SlidingFragment slidingFragment = new SlidingFragment();
Bundle bundle = new Bundle();
bundle.putInt("position", position);
slidingFragment.setArguments(bundle);
return slidingFragment;
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
VerticalViewPager
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 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));
}
}
You can add the PageChangeListener to your view pager and call the onPageSelected() calls, for this you need to have class field called e.g. int mAdCounter = 0:
verticalViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
mAdCount++;
if (mAdCount % 5 == 0) {
//Display your add
//It's better if you load the ad before you need to display it, you can hide the adview and load it
} else {
//Hide the adView
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});

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

Android Viewpager with partial view on 4 fragments

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;
}
}

Animation does not work

Had a little problem. My animation does not work. I don't get any kind of errors. Simply my animation does not work.
This is my code.
public class MainActivity extends FragmentActivity {
private PagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.initialisePaging();
}
private void initialisePaging() {
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this, Tab1Fragment.class.getName()));
fragments.add(Fragment.instantiate(this, Tab2Fragment.class.getName()));
fragments.add(Fragment.instantiate(this, Tab3Fragment.class.getName()));
this.mPagerAdapter = new PagerAdapter(super.getSupportFragmentManager(), fragments);
ViewPager pager = (ViewPager)super.findViewById(R.id.pager);
pager.setAdapter(this.mPagerAdapter);
pager.setPageTransformer(true, new ZoomOutPageTransformer());
}
public static class Tab1Fragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container == null) {
return null;
}
return (ImageView)inflater.inflate(R.layout.tab_frag1_layout, container, false);
}
}
public static class Tab2Fragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container == null) {
return null;
}
return (ImageView)inflater.inflate(R.layout.tab_frag2_layout, container, false);
}
}
public static class Tab3Fragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container == null) {
return null;
}
return (ImageView)inflater.inflate(R.layout.tab_frag3_layout, container, false);
}
}
public static class PagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public PagerAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
#Override
public int getCount() {
return this.fragments.size();
}
}
public static class ZoomOutPageTransformer implements ViewPager.PageTransformer {
private static final float MIN_SCALE = 0.85f;
private static final float MIN_ALPHA = 0.5f;
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);
ViewHelper.setAlpha(view, 0);
} else if (position <= 1) { // [-1,1]
// Modify the default slide transition to shrink the page as well
float scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position));
float vertMargin = pageHeight * (1 - scaleFactor) / 2;
float horzMargin = pageWidth * (1 - scaleFactor) / 2;
if (position < 0) {
// view.setTranslationX(horzMargin - vertMargin / 2);
ViewHelper.setTranslationX(view, horzMargin - vertMargin / 2);
} else {
// view.setTranslationX(-horzMargin + vertMargin / 2);
ViewHelper.setTranslationX(view, -horzMargin + vertMargin / 2);
}
// Scale the page down (between MIN_SCALE and 1)
// view.setScaleX(scaleFactor);
// view.setScaleY(scaleFactor);
ViewHelper.setScaleX(view, scaleFactor);
ViewHelper.setScaleY(view, scaleFactor);
// Fade the page relative to its size.
// view.setAlpha(MIN_ALPHA +
// (scaleFactor - MIN_SCALE) /
// (1 - MIN_SCALE) * (1 - MIN_ALPHA));
ViewHelper.setAlpha(view, MIN_ALPHA +
(scaleFactor - MIN_SCALE) /
(1 - MIN_SCALE) * (1 - MIN_ALPHA));
} else { // (1,+Infinity]
// This page is way off-screen to the right.
// view.setAlpha(0);
ViewHelper.setAlpha(view, 0);
}
}
}
}
Every thing else is working fine. I want to implement this. please help me.
Before i implemented without using NineOldroids. But even after implementing this, it didn't work.
I also have that problem check out this answer. Using nineoldandroid should work but PageTransform is ignored in pre 11 (Heneycomb) although it's in the support library. I'm thinking of moving to view flipper just to do the animation. But i'm still searching for another way.
EDIT: CHeck out my answer in that Question to see how i resolved the issue. I basicly copied the viewpager class and removed the if statement that checked the SDK version in setPageTransformer
It did not work in emulator with android 2.2 platform, but when i checked in my Phone Sony Xperia Tipo Dual having ICS as platform, it worked.

Categories

Resources