Android实现显示在屏幕底部的自定义Dialog
编写一个类BottomFullDialog继承自Dialog,需要重写里面的构造方法和onCreate方法。
public class BottomFullDialog extends Dialog { public BottomFullDialog(Context context) { super(context); } public BottomFullDialog(Context context, int themeResId) { super(context, themeResId); View contentView = getLayoutInflater().inflate( R.layout.dialog_bottomfull, null); requestWindowFeature(Window.FEATURE_NO_TITLE); contentView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { BottomFullDialog.this.dismiss(); return true; } }); super.setContentView(contentView); } protected BottomFullDialog(Context context, boolean cancelable, OnCancelListener cancelListener) { super(context, cancelable, cancelListener); } @SuppressWarnings("deprecation") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setGravity(Gravity.BOTTOM);//设置显示在底部 WindowManager windowManager=getWindow().getWindowManager(); Display display= windowManager.getDefaultDisplay(); WindowManager.LayoutParams layoutParams=getWindow().getAttributes(); layoutParams.width=display.getWidth();//设置Dialog的宽度为屏幕宽度 getWindow().setAttributes(layoutParams); } }
![](https://images2015.cnblogs.com/blog/894812/201604/894812-20160412142748988-2114323681.png)
dialog_bottomfull.xml布局文件
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:layout_width="match_parent" android:layout_height="200dp" android:background="#ffffff" android:gravity="center"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="自定义Dialog里面的内容" android:textColor="#000000" /> </LinearLayout> </FrameLayout>
在styles.xml文件里面新建节点:
<style name="BottomFullDialog" parent="@style/Theme.AppCompat.Dialog"> <item name="android:windowBackground">@color/white40</item> <item name="android:windowAnimationStyle">@style/dialog_animation</item> </style> <style name="dialog_animation" parent="android:Animation"> <item name="@android:windowEnterAnimation">@anim/dialog_enter</item> <item name="@android:windowExitAnimation">@anim/dialog_exit</item> </style>
anim文件夹里新建文件dialog_enter.xml
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android"> <translate android:duration="200" android:toYDelta="0%" android:fillAfter="true" android:fromYDelta="100%p" /> </set>
dialog_exit.xml文件
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android"> <translate android:duration="200" android:fromYDelta="0%" android:fillAfter="true" android:toYDelta="100%p" /> </set>
调用方法:
BottomFullDialog bottomFullDialog=new BottomFullDialog(this,R.style.BottomFullDialog); bottomFullDialog.setCancelable(true); bottomFullDialog.setCanceledOnTouchOutside(true); bottomFullDialog.show();