gpt4 book ai didi

android - 在启动 CustomViewPager 时启动动画

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:10:53 27 4
gpt4 key购买 nike

我成功地在我的 CustomViewPager 开始时创建了一个动画,它的作用类似于轮播。所以在这里,我的元素在 3 秒内从左边来到右边。问题是它只是一个翻译我想知道是否有可能让我的 viewpager 从远处滚动到他的最终位置。

你有办法做到这一点吗?问候。

编辑:因此,我尝试了其他方法,并创建了我的自定义 ScrollToAnimation。我成功地创造了我想要的东西,但运动并不顺利,你能帮帮我吗?我的新代码:

import android.support.v4.view.ViewPager;
import android.view.animation.Animation;
import android.view.animation.Transformation;

import java.util.Calendar;

public class ScrollToAnimation extends Animation {
private int currentIndex = 0, nbChilds = -1, deltaT = 0;
private float fromX, toX;
private long animationStart;
private ViewPager viewpager;

public ScrollToAnimation(ViewPager viewpager, float fromX, float toX, int duration) {
this.viewpager = viewpager;
this.fromX = fromX;
this.toX = toX;

nbChilds = viewpager.getChildCount();
deltaT = duration / nbChilds;

setDuration(duration);
animationStart = Calendar.getInstance().getTimeInMillis();
}

@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
super.applyTransformation(interpolatedTime, t);
int offset = (int) (-fromX * interpolatedTime + fromX);
viewpager.scrollTo(offset, 0);

long animationProgression = Calendar.getInstance().getTimeInMillis() - animationStart;
currentIndex = (int) (animationProgression/deltaT);
if(viewpager.getCurrentItem() != currentIndex) {
viewpager.setCurrentItem(nbChilds-currentIndex, false);
}
}
}

ViewPager:

import android.content.Context;
import android.graphics.Canvas;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.animation.Animation;
import android.view.animation.Interpolator;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class CarouselViewPager extends ViewPager {
private DisplayMetrics metrics;
private Animation animation;
private SpeedScroller mScroller = null;
private boolean animationNotStarted = true, leftToRight;

public CarouselViewPager(Context context) {
super(context);
postInitViewPager();
metrics = getContext().getResources().getDisplayMetrics();
}

public CarouselViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
postInitViewPager();
metrics = getContext().getResources().getDisplayMetrics();
}

private void postInitViewPager() {
try {
Class<?> viewpager = ViewPager.class;
Field scroller = viewpager.getDeclaredField("mScroller");
scroller.setAccessible(true);
Field interpolator = viewpager.getDeclaredField("sInterpolator");
interpolator.setAccessible(true);

mScroller = new SpeedScroller(getContext(), (Interpolator) interpolator.get(null));
scroller.set(this, mScroller);
} catch (Exception e) {
Log.e("postInitViewPager", e.getMessage());
}
}

public void setScrollDurationFactor(double scrollFactor) {
mScroller.setScrollDurationFactor(scrollFactor);
}

@Override
public void setCurrentItem(int item, boolean smoothScroll) {
try {
Method method = ViewPager.class.getDeclaredMethod("setCurrentItemInternal", int.class, boolean.class, boolean.class, int.class);
method.setAccessible(true);
method.invoke(this, item, true, false, 1500);
} catch (Exception e) {
e.printStackTrace();
super.setCurrentItem(item, smoothScroll);
}
}

public void startAnimation(boolean leftToRight) {
animation = new ScrollToAnimation(this, ((metrics.widthPixels/2)+200)*2, 0, 2000);
animationNotStarted = false;
this.leftToRight = leftToRight;
}

private Canvas enterAnimation(final Canvas c) {
animationNotStarted = true;
startAnimation(animation);
scrollTo(0, 0);
return c;
}

@Override
protected void onDraw(Canvas canvas) {
if (!animationNotStarted) {
canvas = enterAnimation(canvas);
}
super.onDraw(canvas);
}
}

编辑2:

这里有一个屏幕截图可以帮助您了解我想要什么。实际上我有一个像这样的自定义 viewpager :

enter image description here

我想要的动画如下:

  • 当我启动动画时,项目在很远的地方。
  • 之后,它们从左到右(或相反)并停在所选项目上,但我希望在项目滚动时具有缩放效果。
  • 借助自定义适配器,我成功创建了缩放效果

我的问题,这里是当我设置当前项目时它不流畅,你有什么想法吗?这是代码适配器

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
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 android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;

public class CarouselAdapter extends FragmentPagerAdapter implements ViewPager.OnPageChangeListener {
private float scale;
private MainActivity context;

private FragmentManager fragmentManager;
private ArrayList<Entity> entities = new ArrayList<>();
private ScaledFrameLayout cur = null, next = null;

public CarouselAdapter(MainActivity context, FragmentManager fragmentManager, ArrayList<Entity> mData) {
super(fragmentManager);
this.fragmentManager = fragmentManager;
this.context = context;
this.entities = mData;
}

@Override
public Fragment getItem(int position) {
if (position == MainActivity.FIRST_PAGE) {
scale = MainActivity.BIG_SCALE;
} else {
scale = MainActivity.SMALL_SCALE;
}
Fragment fragment = CarouselFragment.newInstance(context, entities.get(position), position, scale);
return fragment;
}

@Override
public int getItemPosition(Object object) {
return super.getItemPosition(object);
}

@Override
public int getCount() {
return entities.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 < entities.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 ScaledFrameLayout getRootView(int position) {
return (ScaledFrameLayout) fragmentManager.findFragmentByTag(this.getFragmentTag(position)).getView().findViewById(R.id.rootItem);
}

private String getFragmentTag(int position) {
return "android:switcher:" + context.carousel.getId() + ":" + position;
}
}

更简单的方法是改变当前项目的当前位置而不刷新所有内容,这可能吗?我的意思是不进行任何转换,因为如您所见,我已经有了翻译,当我设置当前项目时,结果与我的带有偏移量的 scrollto 发生冲突。

最佳答案

我认为您必须使 imageSlider 中的一个具有平滑滚动和图像随动画变化。

github 中提供的 Android Image Slider 库现在请参阅以下步骤以使用它。

  • 第 1 步:在 lib 下编译 Gradle。

    dependencies {
    compile "com.android.support:support-v4:+"
    compile 'com.squareup.picasso:picasso:2.3.2'
    compile 'com.nineoldandroids:library:2.4.0'
    compile 'com.daimajia.slider:library:1.1.5@aar'
    }
  • 第 2 步:向您的 AndroidManifest.xml 添加权限(如有必要)

     <!-- if you want to load images from the internet -->
    <uses-permission android:name="android.permission.INTERNET" />

    <!-- if you want to load images from a file OR from the internet -->
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
  • 第 3 步:将 slider 添加到您的布局:

    <com.daimajia.slider.library.SliderLayout
    android:id="@+id/slider"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    />

    现在在您的 Activity 中编写代码,在此处 SlideShow.class 中管理代码。

     public class SlideShow extends Activity {
    ImageView mIVmenu;
    SliderLayout sliderLayout;
    ListView menu_list;
    ArrayList<String> imgList = new ArrayList<String>();
    int position;
    Button btnBack;
    static int adapter_position = 0;
    String animation_name;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.slideshow);
    sliderLayout = (SliderLayout) findViewById(R.id.sliderlayout);
    menu_list = (ListView) findViewById(R.id.menu_list);
    btnBack = (Button) findViewById(R.id.btn_back_slideshow);
    menu_list.setAdapter(adapter);
    // get Data from Intent array list and set on array list
    imgList = getIntent().getStringArrayListExtra("arrayList");
    position = getIntent().getExtras().getInt("position");
    animation_name = SliderLayout.Transformer.Default.toString();
    }

    // call method for set images in slideshow and configure slideshow..
    addImagesToSlider();

    btnBack.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    Intent i = new Intent(SlideShow.this, MainActivity.class);
    startActivity(i);
    finish();
    }
    });

    }

    private void addImagesToSlider() {
    for (int i = 0; i < imgList.size(); i++) {
    TextSliderView textSliderView = new TextSliderView(this);
    textSliderView.description("").image(new File(imgList.get(i))).setScaleType(BaseSliderView.ScaleType.CenterInside).setOnSliderClickListener(new BaseSliderView.OnSliderClickListener() {
    @Override
    public void onSliderClick(BaseSliderView slider) {
    }
    });
    sliderLayout.addSlider(textSliderView);
    }

    sliderLayout.setPresetTransformer(animation_name);
    sliderLayout.setCustomAnimation(new DescriptionAnimation());
    sliderLayout.stopAutoCycle();
    sliderLayout.setCurrentPosition(position);
    }

    BaseAdapter adapter = new BaseAdapter() {
    @Override
    public int getCount() {
    return SliderLayout.Transformer.values().length;
    }

    @Override
    public Object getItem(int position) {
    return null;
    }

    @Override
    public long getItemId(int position) {
    return 0;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

    View view;
    view = LayoutInflater.from(parent.getContext()).inflate(R.layout.slidemenu_item, parent, false);
    TextView tv = (TextView) view.findViewById(R.id.txtslideTitle);
    final String str = SliderLayout.Transformer.values()[position].toString();
    tv.setText(str);

    view.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

    sliderLayout.setPresetTransformer(str);
    animation_name = str;
    notifyDataSetChanged();

    }
    });
    if (str.equals(animation_name)) {
    adapter_position = position;
    tv.setBackgroundColor(getResources().getColor(R.color.colorAccent));
    } else { tv.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
    }
    return view;
    }
    };
    }

更多信息引用this

关于android - 在启动 CustomViewPager 时启动动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36550272/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com