动画 AlertDialog 的入口和出口

Gau*_*tam 9 animation android android-alertdialog android-dialogfragment

我必须AlertDialog在它进入时滑入并在它被解散时滑出,但它没有动画。

那么如何让动画工作呢?

这是我所拥有的

public class SlideDialogFragment extends DialogFragment {
     @Override
     public Dialog onCreateDialog(Bundle savedInstanceState) {
              return  new AlertDialog.Builder(new ContextThemeWrapper(getActivity(),R.style.SlidingDialog))
                      .setTitle("Sliding dialog")
                      .create()
     }
Run Code Online (Sandbox Code Playgroud)

主题文件

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
    <style name="SlidingDialog" parent="@android:style/Theme.DeviceDefault.Dialog">
        <item name="android:windowAnimationStyle">@style/SlidingDialogAnimation</item>
    </style>
    <style name="SlidingDialogAnimation">
        <item name="android:windowEnterAnimation">@android:anim/slide_in_left</item>
        <item name="android:windowExitAnimation">@android:anim/slide_out_right</item>
    </style>
</resources>
Run Code Online (Sandbox Code Playgroud)

我参考了太多资源,似乎没有一种适合我的正确方法可以做到这一点,可能是我遗漏了一些东西

我在用

  • 安卓系统
  • 应用程序是为 API 15+ 构建的

以下是一些我无法从中得到答案的相关资源

Har*_*eet 8

这是使用上述参考和代码的工作代码。

// Declare a Builder.
AlertDialog.Builder builder = new AlertDialog.Builder(context);

// You can even inflate a layout to the AlertDialog.Builder, if looking to create a custom one.
// Add and fill all required builder methods, as per your need.


// Now create object of AlertDialog from the Builder.
final AlertDialog dialog = builder.create();

// Let's start with animation work. We just need to create a style and use it here as follows.
if (dialog.getWindow() != null)
    dialog.getWindow().getAttributes().windowAnimations = R.style.SlidingDialogAnimation;

dialog.show();
Run Code Online (Sandbox Code Playgroud)

关于样式,我使用了与问题相同的样式(在styles.xml 中)。

<style name="SlidingDialogAnimation">
        <item name="android:windowEnterAnimation">@android:anim/slide_in_left</item>
        <item name="android:windowExitAnimation">@android:anim/slide_out_right</item>
</style>
Run Code Online (Sandbox Code Playgroud)

但是您可以通过在 res/anim 文件夹中放置动画 XML 文件来使用任何其他自定义文件。

谢谢。