Android Dialog 弹框放大缩小动画实现,不超出页面!
可以通过以下步骤实现 dialog 弹框放大缩小不出页面:
-
在布局文件中定义一个 FrameLayout,作为 dialog 弹框的容器。
-
创建一个自定义的 Dialog 类,继承自 Dialog,并在构造方法中设置 Dialog 的样式为无标题栏且背景透明。
public class CustomDialog extends Dialog {
public CustomDialog(Context context) {
super(context, R.style.DialogTheme);
setContentView(R.layout.dialog_layout);
getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
}
}
-
在 dialog_layout.xml 中定义一个自己想要的布局。
-
在 Activity 中创建 CustomDialog 对象,并设置其显示在 FrameLayout 中。同时,可以为 FrameLayout 设置一个动画效果来实现放大缩小的效果。
final FrameLayout container = findViewById(R.id.container);
final CustomDialog dialog = new CustomDialog(this);
container.addView(dialog.getWindow().getDecorView());
container.setScaleX(0.7f);
container.setScaleY(0.7f);
container.animate().scaleX(1).scaleY(1).setDuration(500).start();
dialog.show();
其中,container 为 FrameLayout 对象,dialog 为 CustomDialog 对象。在添加 CustomDialog 到 FrameLayout 中时,需要调用 getWindow().getDecorView() 方法获取到 CustomDialog 的根 View,才能将其添加到 FrameLayout 中。
在设置动画效果时,可以使用 View.animate() 方法来实现,通过设置 scaleX 和 scaleY 属性来实现放大缩小的效果。最后,调用 CustomDialog 的 show() 方法来显示弹框。
完整代码如下:
dialog_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffffff"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
CustomDialog.java:
public class CustomDialog extends Dialog {
public CustomDialog(Context context) {
super(context, R.style.DialogTheme);
setContentView(R.layout.dialog_layout);
getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
}
}
MainActivity.java:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final FrameLayout container = findViewById(R.id.container);
final CustomDialog dialog = new CustomDialog(this);
container.addView(dialog.getWindow().getDecorView());
container.setScaleX(0.7f);
container.setScaleY(0.7f);
container.animate().scaleX(1).scaleY(1).setDuration(500).start();
dialog.show();
}
}
原文地址: https://www.cveoy.top/t/topic/ozPV 著作权归作者所有。请勿转载和采集!