当用户点击 ListView
中的一行时,我会显示一个 DialogFragment
。我想为对话框的显示设置动画,使其从行的中心开始增长。从启动器打开文件夹时可以看到类似的效果。
我的一个想法是结合使用 TranslateAnimation
和 ScaleAnimation
。还有其他方法吗?
最佳答案
作为 DialogFragment
一个 Dialog
类的包装器,你应该为你的基础 Dialog
设置一个主题来获得你想要的动画:
public class CustomDialogFragment extends DialogFragment implements OnEditorActionListener
{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
// Set a theme on the dialog builder constructor!
AlertDialog.Builder builder =
new AlertDialog.Builder( getActivity(), R.style.MyCustomTheme );
builder
.setTitle( "Your title" )
.setMessage( "Your message" )
.setPositiveButton( "OK" , new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which) {
dismiss();
}
});
return builder.create();
}
}
然后您只需要定义包含所需动画的主题即可。在 styles.xml 中添加您的自定义主题:
<style name="MyCustomTheme" parent="@android:style/Theme.Panel">
<item name="android:windowAnimationStyle">@style/MyAnimation.Window</item>
</style>
<style name="MyAnimation.Window" parent="@android:style/Animation.Activity">
<item name="android:windowEnterAnimation">@anim/anim_in</item>
<item name="android:windowExitAnimation">@anim/anim_out</item>
</style>
现在在 res/anim 文件夹中添加动画文件:
(android:pivotY
是关键)
anim_in.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale
android:interpolator="@android:anim/linear_interpolator"
android:fromXScale="0.0"
android:toXScale="1.0"
android:fromYScale="0.0"
android:toYScale="1.0"
android:fillAfter="false"
android:startOffset="200"
android:duration="200"
android:pivotX = "50%"
android:pivotY = "-90%"
/>
<translate
android:fromYDelta="50%"
android:toYDelta="0"
android:startOffset="200"
android:duration="200"
/>
</set>
anim_out.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale
android:interpolator="@android:anim/linear_interpolator"
android:fromXScale="1.0"
android:toXScale="0.0"
android:fromYScale="1.0"
android:toYScale="0.0"
android:fillAfter="false"
android:duration="200"
android:pivotX = "50%"
android:pivotY = "-90%"
/>
<translate
android:fromYDelta="0"
android:toYDelta="50%"
android:duration="200"
/>
</set>
最后,棘手的事情是让您的动画从每行的中心开始增长。我想该行水平填充屏幕,所以一方面 android:pivotX
值将是静态的。另一方面,您不能以编程方式修改 android:pivotY
值。
我的建议是,您定义几个动画,每个动画在 android:pivotY
属性上都有不同的百分比值(以及引用这些动画的几个主题)。然后,当用户点击该行时,以屏幕上该行的百分比计算 Y 位置。知道百分比位置后,为您的对话框分配一个具有适当 android:pivotY
值的主题。
这不是一个完美的解决方案,但可以为您解决问题。如果您不喜欢结果,那么我建议您忘记 DialogFragment
并为从行的确切中心生长的简单 View
设置动画。
祝你好运!
关于android - 显示 DialogFragment 动画从一个点开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13402782/