我正在尝试slide-in/slide-out
在Fragments
. 我知道StackOverflow上有很多类似的问题,但相信我 - 我尝试了所有这些问题,但没有一个有效。
按照我的代码(基本上取自类似问题):
自定义布局
public class SlidingFrameLayout extends FrameLayout {
public SlidingFrameLayout(Context context) {
super(context);
}
public SlidingFrameLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public float getXFraction() {
final int width = getWidth();
if (width != 0) return getX() / getWidth();
else return getX();
}
public void setXFraction(float xFraction) {
final int width = getWidth();
setX((width > 0) ? (xFraction * width) : -9999);
}
}
分片交易
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.setCustomAnimations(R.animator.card_enter_right, R.animator.card_out_left);
ft.replace(R.id.quiz_container, CardFragment.newInstance());
ft.commit();
对象动画师
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="1000"
android:interpolator="@android:anim/linear_interpolator"
android:propertyName="xFraction"
android:valueFrom="1.0"
android:valueTo="0.0"
android:valueType="floatType" />
布局文件
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.my.package.views.SlidingFrameLayout
android:id="@+id/quiz_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- Other views -->
</FrameLayout>
所以当我运行这段代码时,什么都没有发生。片段被替换但没有动画。
做错了什么?
注意:如果我使用"x"
而不是运行动画"xFraction"
并更改值以假设from:1280 to:0
它正在工作。不幸的是,这对我来说不是一个解决方案,因为我需要一个“百分比值”,因为显示分辨率范围很广。
解决方案
感谢pskink引导我找到解决方案。我一直以为我Fragment的容器需要实现getXFraction()/setXFraction()方法。但事实并非如此。你的 Fragments 布局需要实现getXFraction()/setXFraction
。所以基本上我改变了我的片段布局,如下所示:
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:prefix="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="40dp"
prefix:cardCornerRadius="4dp">
<!-- Content -->
</android.support.v7.widget.CardView>
至:
<com.my.package.views.SlidingFrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:prefix="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="40dp"
prefix:cardCornerRadius="4dp">
<!-- Content -->
</android.support.v7.widget.CardView>
</com.my.package.views.SlidingFrameLayout>