问题描述
我想实现我的应用程序视差效果。我有一个 FragmentActivity
实现 OnPageChangeListener
接口,并听我的 ViewPager
滚动事件。
I'm trying to achieve a parallax effect in my application.I have a FragmentActivity
that implements the OnPageChangeListener
interface and listens to my ViewPager
scrolling events.
要达到这个效果在我的XML我有一个的LinearLayout
的背后都与我的背景其他意见,我谨在 onPageScrolled
回调。如果我只是轻扫这一切ok,效果的作品和背景的位置变化。但是,当我的手指离开屏幕,背景是在他原来的位置重新绘制(即使我在一个新的页面)。我不明白为什么会这样。这里的code我的 FragmentActivity
:
To achieve this effect in my XML I have a LinearLayout
behind all the other views with my background, and I move it in the onPageScrolled
callback.If I simply swipe it's all ok, the effect works and the background position change. But when my finger leaves the screen, the background is redrawn at his original position (even if I'm in a new page).I can't understand why this happens.Here the code of my FragmentActivity
:
public class MainActivity extends FragmentActivity implements OnPageChangeListener {
// DEFINE THE PAGEADAPTER
private ViewPager viewPager;
private com.angtrim.ecomilano.PagerAdapter pagerAdapter;
private int oldPosition = 0;
private int offSet = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// CREATE VIEWPAGER
viewPager = (ViewPager) findViewById(R.id.viewpager);
pagerAdapter = new PagerAdapter(getApplicationContext(),getSupportFragmentManager());
// SET THE ADAPTER
viewPager.setAdapter(pagerAdapter);
// SET FIRST ITEM
viewPager.setCurrentItem(0);
// SET CHANGE PAGE LISTENER
viewPager.setOnPageChangeListener(this);
}
@Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// RIGHT SWIPE
if((oldPosition < arg2))
{
offSet = (int)((arg2 - oldPosition)*0.5);
oldPosition = arg2;
}
// LEFT SWIPE
else if( (oldPosition > arg2))
{
offSet = (int) (-(oldPosition - arg2)*0.5);
oldPosition = arg2;
}
findViewById(R.id.backi).offsetLeftAndRight(offSet);
}
@Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
}
}
感谢你。
推荐答案
我知道,这是一个有点老,但看看到https://github.com/xgc1986/ParallaxPagerLibrary
I know that it's a bit old but take a look to that https://github.com/xgc1986/ParallaxPagerLibrary
这不是覆盖的OnDraw方法,而不是只与图像的效果,它与每一种观点
It not overrides the onDraw method, and the effect not only with images, it works with every kind of view
mPager.setPageTransformer(false, new ParallaxTransformer(R.id.parallaxContent));
R.id.paraallaxContent是观之,你想有这样的效果的ID
R.id.paraallaxContent is the id of the View you want to have this effect
除非其他的解决方案,不需要任何任何混凝土结构的工作,也是布局独立
unless the other solutions, don't need any any concrete structure to work, and also is layout independant
演示:的YouTube
这篇关于Android的视差效果和查看传呼机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!