Android-实现底部弹出PopupWindow并让背景逐渐变暗

Android-实现底部弹出PopupWindow并让背景逐渐变暗

在android开发中,经常需要通过点击某个按钮弹出对话框或者选择框,通过Dialog或者PopupMenu、PopupWindow都能实现。

这里主要介绍后两者:PopupMenu、PopupWindow的实现。 先看两个效果图左边PopupMenu,右边PopupWindow:

      • Android-实现底部弹出PopupWindow并让背景逐渐变暗

        • 一PopupMenu实现
        • 二PopupWindow实现

一、PopupMenu实现:

PopupMenu实现起来比较简单,主要用来实现根据按钮附近弹出的对话框。

  • 首先定义一个menu文件\res\menu\headmenu.xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools" tools:context="com.arbo.hero.LoginActivity">
    <item
        android:id="@+id/camera"
        android:title="拍照"
        android:orderInCategory="100"
        app:showAsAction="never" />
    <item
        android:id="@+id/gallery"
        android:title="从相册中选取"
        android:orderInCategory="100"
        app:showAsAction="never" />
    <item
        android:id="@+id/cancel"
        android:title="取消"
        android:orderInCategory="100"
        app:showAsAction="never" />

</menu>
  • 创建一个PopupMenu并添加点击事件:
private void showPopmenu(View view){
        popupMenu = new PopupMenu(this,view);
        popupMenu.getMenuInflater().inflate(R.menu.headmenu,popupMenu.getMenu());
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch(item.getItemId()){
                    case R.id.camera:
                        Toast.makeText(HeadPortrait.this,"Click camera",Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.gallery:
                        Toast.makeText(HeadPortrait.this,"Click gallery",Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.cancel:
                        Toast.makeText(HeadPortrait.this,"Click cancel",Toast.LENGTH_SHORT).show();
                        break;
                }
                return false;
            }
        });
        popupMenu.show();
    }
  • MainActivity很简单,点击按钮调用showPopmenu()方法即可:
public class MainActivity extends Activity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //main.xml页面主布局只有一个按钮,这里就不贴代码了
        setContentView(R.layout.main);
        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //点击按钮就创建并显示一个popupMenu
                showPopmenu(btnmenu);
            }
        }
    }
}

以上,就实现了利用PopupMenu在按钮附近弹出一个选择框。

PopupMenu的优点:简单;根据菜单大小自适应位置,在按钮附近弹出;适合某些情景。

缺点:形式比较单一,效果一般。

.


二、PopupWindow实现:

相比之下,PopupWindow的实现复杂一些,但是自定义性更强,它可以将任意界面设置为PopupWindow。

  • 先看弹出window布局window_popup.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="match_parent"
    android:layout_marginLeft="@dimen/activity_horizontal_margin"
    android:layout_marginRight="@dimen/activity_horizontal_margin"
    android:background="#dadada"
    android:orientation="vertical">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <Button
            android:id="@+id/camera"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="拍照"
            android:background="#f0f0f0"
            />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#2d2c2c"
            />
        <Button
            android:background="#f0f0f0"
            android:id="@+id/gallery"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="从手机相册选择"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#2d2c2c"
            />
        <Button
            android:background="#f0f0f0"
            android:id="@+id/savepicture"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="保存图片"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:orientation="vertical">

        <Button
            android:background="#f0f0f0"
            android:id="@+id/cancel"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="取消"
            />
    </LinearLayout>
</LinearLayout>

布局的效果图:

  • 创建popupWindow并为其添加点击事件:
void bottomwindow(View view) {
        if (popupWindow != null && popupWindow.isShowing()) {
            return;
        }
        LinearLayout layout = (LinearLayout) getLayoutInflater().inflate(R.layout.window_popup, null);
        popupWindow = new PopupWindow(layout,
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        //点击空白处时,隐藏掉pop窗口
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        //添加弹出、弹入的动画
        popupWindow.setAnimationStyle(R.style.Popupwindow);
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        popupWindow.showAtLocation(view, Gravity.LEFT | Gravity.BOTTOM, 0, -location[1]);
        //添加按键事件监听
        setButtonListeners(layout);
        //添加pop窗口关闭事件,主要是实现关闭时改变背景的透明度
        popupWindow.setOnDismissListener(new poponDismissListener());
        backgroundAlpha(1f);
    }
  • 事件监听的函数setButtonListeners() :
private void setButtonListeners(LinearLayout layout) {
        Button camera = (Button) layout.findViewById(R.id.camera);
        Button gallery = (Button) layout.findViewById(R.id.gallery);
        Button savepicture = (Button) layout.findViewById(R.id.savepicture);
        Button cancel = (Button) layout.findViewById(R.id.cancel);

        camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (popupWindow != null && popupWindow.isShowing()) {
                    //在此处添加你的按键处理 xxx
                    popupWindow.dismiss();
                }
            }
        });
        gallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (popupWindow != null && popupWindow.isShowing()) {
                    //在此处添加你的按键处理 xxx
                    popupWindow.dismiss();
                }
            }
        });
        savepicture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (popupWindow != null && popupWindow.isShowing()) {
                    //在此处添加你的按键处理 xxx
                    popupWindow.dismiss();
                }
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                }
            }
        });
    }
  • 弹出、收回的动画:

    若res文件夹下没有anim目录,则自己添加一个:new–>Android resource directory 名字填anim。然后新建两个tranlate文件:

弹出 window_out.xml :

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/decelerate_interpolator"
    android:fromYDelta="100%" android:toYDelta="0"
    android:duration="300"/>

收回 window_back.xml:

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:fromYDelta="0" android:toYDelta="100%"
    android:duration="200"/>
  • 然后在style.xml中添加我们的这两个动画:
<style name="Popupwindow">
        <item name="android:windowEnterAnimation">@anim/window_out</item>
        <item name="android:windowExitAnimation">@anim/window_back</item>
    </style>

还是上面的同一个MainActivity,把按钮点击事件的处理函数换成popupwindow的即可:

btnmenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bottomwindow(btnmenu);
                }
        }

.

以上,就可以实现这样的点击按钮从屏幕底部弹出window窗口的效果,如下:

但是,这样的效果并不好,我们希望弹出windows的时候,其他背景可以变成半透明,这样可以突出重点。网上的方法是通过这段代码来改变背景的透明度的:

/**
     * 设置添加屏幕的背景透明度
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha)
    {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);           getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    }

然后在弹出的时候将背景设为半透明:

bottomwindow(btnmenu);
backgroundAlpha(0.5f);

在返回的时候设置回来:

backgroundAlpha(1f);

这的确是可以实现效果,但是点击的时候突然变暗和变亮,效果不太好!如下:

我希望是弹出的过程中,慢慢变暗。是有一个过程的,而不是一下子就暗下来了。这里利用延时和Handler来动态地改变背景的透明度。

//在调用弹出的方法后,开启一个子线程
            @Override
            public void onClick(View view) {
                bottomwindow(btnmenu);
                new Thread(new Runnable(){
                    @Override
                    public void run() {
                        while(alpha>0.5f){
                            try {
                                //4是根据弹出动画时间和减少的透明度计算
                                Thread.sleep(4);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            Message msg =mHandler.obtainMessage();
                            msg.what = 1;
                            //每次减少0.01,精度越高,变暗的效果越流畅
                            alpha-=0.01f;
                            msg.obj =alpha ;
                            mHandler.sendMessage(msg);
                        }
                    }

                }).start();
            }

同理,返回的时候把透明度跳回来:

/**
     * 返回或者点击空白位置的时候将背景透明度改回来
     */
    class poponDismissListener implements PopupWindow.OnDismissListener{

        @Override
        public void onDismiss() {
            // TODO Auto-generated method stub
            new Thread(new Runnable(){
                @Override
                public void run() {
                    //此处while的条件alpha不能<= 否则会出现黑屏
                    while(alpha<1f){
                        try {
                            Thread.sleep(4);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        Log.d("HeadPortrait","alpha:"+alpha);
                        Message msg =mHandler.obtainMessage();
                        msg.what = 1;
                        alpha+=0.01f;
                        msg.obj =alpha ;
                        mHandler.sendMessage(msg);
                    }
                }

            }).start();
        }

    }

在Handler里面我们调用改变背景透明的方法即可:

Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    backgroundAlpha((float)msg.obj);
                    break;
            }
        }
    };

这样修改以后,效果是这样的:

以上,基本达到了逐渐变暗、变量的目的。

如果大家发现什么问题或者有更好的方法,欢迎指出,谢谢!

时间: 2024-08-11 03:22:29

Android-实现底部弹出PopupWindow并让背景逐渐变暗的相关文章

转 android 从底部弹出一个popuwindow,渐入渐出效果。我这里是用在购物车需要选择购买选项的操作。

最近要改客户端,需要实现一个从底部弹出的popuwindow,像我这种渣渣android技术,能整出popuwindow但是整不出动画,百度之,记录一下. 从下面这个地址转的 http://blog.csdn.net/yxhuang2008/article/details/42617805 最近因为要用到PopupWindow,所以,就在网上搜索了一下,发现挺多关于这样的文章,现在我把它们整理了一下. 1.Android PopupWindow 的使用技巧,http://www.cnblogs.

android Dialog 底部弹出

. if (dialShareDialog == null) { dialShareDialog = new Dialog(context, R.style.dialog); dialShareDialog.setContentView(R.layout.dialog_share); dialShareDialog.setCanceledOnTouchOutside(true); // 获取对话框的窗口,并设置窗口参数 WindowManager.LayoutParams lp=dialShar

【Android】android PopupWindow实现从底部弹出或滑出选择菜单或窗口

转载自:android PopupWindow实现从底部弹出或滑出选择菜单或窗口 Android PopupWindow的使用和分析 Popupwindow的使用 PopupWindow用法

Android 底部弹出提示框的解决办法(使用Activity以及PopupWindow)

本片文章主要谈探讨了如何实现在底部弹出提示框背景为半透明效果的实现.想要实现此种效果一般有两种方式一个是使用Activity设置Theme另一种方式就是使用PopupWindow设置样式实现效果. 一,使用Activity 首先是此activity的布局文件: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.andro

通用的popupwindow底部弹出框

前段时间做项目的时候,有几个底部弹出框,当时因为忙着赶进度所有就单独写了好几个popupwindow.后来就想着怎么实现一个通用的PopupWindow工具类 就是在要用到的时候创建该工具类的对象,并传入相应的框体布局,就可以实现了. 先看看效果,下面的两是调用同一个PopupWindowUtils创建的:       ok,先看看popupWindow的具体实现 import android.app.Activity; import android.graphics.drawable.Colo

Android项目实战(十七):QQ空间实现(二)—— 分享功能 / 弹出PopupWindow

原文:Android项目实战(十七):QQ空间实现(二)-- 分享功能 / 弹出PopupWindow 这是一张QQ空间说说详情的截图. 分析: 1.点击右上角三个点的图标,在界面底部弹出一个区域,这个区域有一些按钮提供给我们操作 2.当该区域出现的时候,详情界面便灰了,也说成透明度变化了 3.当任意选了一个按钮或者点击了该区域以外的部分,该区域消失,灰色界面变回亮白色,并执行点击的按钮对应的操作 显然,这个功能我们需要用PopupWindow实现更好~ --------------------

Android编程:底部弹出的对话框

本文博客链接:http://blog.csdn.net/jdh99,作者:jdh,转载请注明. 环境: 主机:WIN10 开发环境:Android Studio 2.2 Preview 3 说明: 两种方法实现底部弹出的对话框: Dialog DialogFragment 推荐用DialogFragment 效果图: 布局文件dialog_select_call.xml: <?xml version="1.0" encoding="utf-8"?> &l

Android Demo---实现从底部弹出窗口

在前面的博文中,小编简单的介绍了如何制作圆角的按钮以及圆角的图片,伴着键盘和手指之间的舞步,迎来新的问题,不知道小伙伴有没有这样的经历,以App为例,点击头像的时候,会从底部弹出一个窗口,有从相册中选择.拍照.取消的字样,点击相应的按钮,完成相应的操作,在小编做项目的过程中遇到类似的问题,小编经过一番捣鼓,终于搞定了ing,今天这篇博文博文,小编简单的介绍一下,如何点击头像,实现从底部弹出窗口的故事,这个故事实现的是弹出滑动窗口,主要是使用了一些设置Activity的样式来实现弹出效果和滑动效果

PopupWindow底部弹出

说明:从屏幕底部弹出PopupWindow,有弹出隐藏动画效果.背景设置透明度. 效果图例如以下: 1.MainActivity.java   显示popwindow,宽高跟屏幕大小一样,设置一个透明度背景 public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setCo