• Android学习笔记_35_PopupWindow泡泡窗口的实现及GridView应用


      1、PopupWindow是一个可以显示在当前Activity之上的浮动容器,PopupWindow弹出的位置是能够改变的,按照有无偏移量,可以分为无偏移和有便宜两种;按照参照对象的不同又可以分为两种:相对某个控件(Anchor锚点)的位置和在父容器内部的相对位置。

      显示PopupWindow的方法:

    showAsDropDown(Viewanchor) //相对某个控件的位置(正下方),无偏移
    showAsDropDown(Viewanchor, int xoff, int yoff) //相对某个控件的位置,有偏移,xoff X轴的偏移量,yoff Y轴的偏移量
    showAtLocation(Viewparent, int gravity, int x, int y) //在父容器的什么位置,gravity为相对位置,如:正中央Gravity.CENTER、下方Gravity.BOTTOM、
    Gravity.Right|Gravity.BOTTOM右下方等,后面两个参数为x/y轴的偏移量。

        2、创建泡泡窗口的界面:

      android:verticalSpacing="10px"    //垂直间隔 
        android:horizontalSpacing="10px" //横向间隔 
        android:numColumns="auto_fit"    //自适应列数 
        android:columnWidth="60px"        //列宽 
        android:stretchMode="columnWidth" //缩放与列宽大小同步 

      convertView.setLayoutParams(new AbsListView.LayoutParams(45,45)); //有时候需要指定格子的宽度和高度

    <?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:background="@drawable/bg"
        android:orientation="vertical" >
    
        <GridView
            android:id="@+id/gridView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:horizontalSpacing="10dp"
            android:numColumns="4"
            android:verticalSpacing="10dp" />
    </LinearLayout>

      为GridView控件设置背景色,在res/drawable目录创建bg.xml文件:

    <?xml version="1.0" encoding="utf-8" ?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle" >
    
        <gradient
            android:angle="270"
            android:endColor="#1DC9CD"
            android:startColor="#A2E0FB" />
    
        <padding
            android:bottom="2dp"
            android:left="2dp"
            android:right="2dp"
            android:top="2dp" />
    
    </shape>

      泡泡窗口由图片和文字组成,因此为它的项设置布局界面grid_item.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:gravity="center"
        android:orientation="vertical" >
    
        <ImageView
            android:id="@+id/imageView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    
        <TextView
            android:id="@+id/textView"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:textColor="#000099"
            android:textSize="16sp" />
    
    </LinearLayout>

      3、为泡泡窗口设置动画效果:

      设置动画样式:

    <resources>
        <style name="AppBaseTheme" parent="android:Theme.Light">  
        </style>
        <style name="AppTheme" parent="AppBaseTheme">
        </style>
        <style name="animation">
            <item name="android:windowEnterAnimation">@anim/enter</item>
            <item name="android:windowExitAnimation">@anim/out</item>
       </style>
    </resources>

      动画样式需要在res/anim下创建,需要创建进入(enter.xml)和退出(out.xml)两个动画:

    <?xml version="1.0" encoding="utf-8"?>
    <set xmlns:android="http://schemas.android.com/apk/res/android"
        android:shareInterpolator="false" >
        <!-- 设置平移,现在只需要在Y轴上移动 -->
        <translate
            android:duration="500"
            android:fromYDelta="100%p"
            android:toYDelta="0" />
        <!-- 设置透明度 -->
        <alpha
            android:duration="300"
            android:fromAlpha="0.7"
            android:toAlpha="1.0" />
    
    </set>
    <?xml version="1.0" encoding="utf-8"?>
    <set xmlns:android="http://schemas.android.com/apk/res/android"
        android:shareInterpolator="false" >
    
        <translate
            android:duration="3000"
            android:fromYDelta="0"
            android:toYDelta="100%p" />
    
        <alpha
            android:duration="2000"
            android:fromAlpha="1.0"
            android:toAlpha="0.5" />
    </set>

      4、后台代码实现:

    package com.example.popupwindow;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    
    import android.app.Activity;
    import android.graphics.drawable.BitmapDrawable;
    import android.os.Bundle;
    import android.view.Gravity;
    import android.view.Menu;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.GridView;
    import android.widget.ListAdapter;
    import android.widget.PopupWindow;
    import android.widget.SimpleAdapter;
    
    public class MainActivity extends Activity {
        PopupWindow popupWindow;
        View parent;
        private int[] images = { R.drawable.i1, R.drawable.i2, R.drawable.i3,
                R.drawable.i4, R.drawable.i5, R.drawable.i6, R.drawable.i7,
                R.drawable.i8 };
        private String[] names = { "搜索", "文件管理", "下载管理", "全屏", "网址", "书签", "加入书签",
                "分享页面" };
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            // LayoutInflater mLayoutInflater = (LayoutInflater)context.getSystemService(LAYOUT_INFLATER_SERVICE);
            //通过LayoutInflater获取布局界面
            View contentView = getLayoutInflater().inflate(R.layout.popupwin, null);
            //查找popupwin界面的GridView控件
            GridView gridView = (GridView) contentView.findViewById(R.id.gridView);
            //填充数据
            gridView.setAdapter(getAdapter());
            //设置点击事件
            gridView.setOnItemClickListener(new ItemClickListener());
    
            popupWindow = new PopupWindow(contentView,
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
    
            popupWindow.setFocusable(true);// 取得焦点
            // 点击空白的地方关闭PopupWindow
            popupWindow.setBackgroundDrawable(new BitmapDrawable()); 
            //给popupWindow窗口加入动画效果
            popupWindow.setAnimationStyle(R.style.animation);
            parent = this.findViewById(R.id.main);
        }
    
        private final class ItemClickListener implements OnItemClickListener {
            public void onItemClick(AdapterView<?> parent, View view, int position,
                    long id) {
                if (popupWindow.isShowing())
                    popupWindow.dismiss();// 关闭
                // ....
            }
        }
        
        //将图片和名称字段对应到视图界面grid_view的图像和文本上
        private ListAdapter getAdapter() {
            List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
            for (int i = 0; i < images.length; i++) {
                HashMap<String, Object> item = new HashMap<String, Object>();
                item.put("image", images[i]);
                item.put("name", names[i]);
                data.add(item);
            }
            SimpleAdapter simpleAdapter = new SimpleAdapter(this, data,
                    R.layout.grid_item, new String[] { "image", "name" },
                    new int[] { R.id.imageView, R.id.textView });
            return simpleAdapter;
    
        }
        //打开PopupWindow窗口
        public void openPopWindow(View v) {
            //在父窗口的底部显示,没有偏移量
            popupWindow.showAtLocation(parent, Gravity.BOTTOM, 0, 0);
        }
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }
    
    }

     相对某个view的位置显示:

    lv_app_manager.setOnItemClickListener(new OnItemClickListener() {
    
                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {
    
                    // 获取当前view对象在窗体中的位置
                    int[] arrayOfInt = new int[2];
                    view.getLocationInWindow(arrayOfInt);
    
                    int i = arrayOfInt[0] + 60;
                    int j = arrayOfInt[1];
    
                 
                    View popupview = View.inflate(AppManagerActivity.this,  R.layout.popup_item, null);
                    LinearLayout ll_start = (LinearLayout) popupview .findViewById(R.id.ll_start);
                    LinearLayout ll_uninstall = (LinearLayout) popupview.findViewById(R.id.ll_uninstall);
                    LinearLayout ll_share = (LinearLayout) popupview.findViewById(R.id.ll_share);
    
                    // 把当前条目在listview中的位置设置给view对象
                    ll_share.setTag(position);
                    ll_uninstall.setTag(position);
                    ll_start.setTag(position);
    
                    ll_start.setOnClickListener(AppManagerActivity.this);
                    ll_uninstall.setOnClickListener(AppManagerActivity.this);
                    ll_share.setOnClickListener(AppManagerActivity.this);
    
                    LinearLayout ll = (LinearLayout) popupview.findViewById(R.id.ll_popup);
                    ScaleAnimation sa = new ScaleAnimation(0.0f, 1.0f, 0.0f, 1.0f);
    sa.setDuration(
    200); localPopupWindow = new PopupWindow(popupview, 230, 70); // 一定要记得给popupwindow设置背景颜色 // Drawable background = new ColorDrawable(Color.TRANSPARENT); Drawable background = getResources().getDrawable( R.drawable.local_popup_bg); localPopupWindow.setBackgroundDrawable(background); localPopupWindow.showAtLocation(view, Gravity.LEFT | Gravity.TOP, i, j); ll.startAnimation(sa); } });
    private void showPopUp(View v) {  
            LinearLayout layout = new LinearLayout(this);  
            layout.setBackgroundColor(Color.GRAY);  
            TextView tv = new TextView(this);  
            tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));  
            tv.setText("I'm a pop -----------------------------!");  
            tv.setTextColor(Color.WHITE);  
            layout.addView(tv);  
      
            popupWindow = new PopupWindow(layout,120,120);  
              
            popupWindow.setFocusable(true);  
            popupWindow.setOutsideTouchable(true);  
            popupWindow.setBackgroundDrawable(new BitmapDrawable());  
              
            int[] location = new int[2];  
            v.getLocationOnScreen(location);  
              
            popupWindow.showAtLocation(v, Gravity.NO_GRAVITY, location[0], location[1]-popupWindow.getHeight());  
        }  
    pop = new PopupWindow(  
                                layout,  
                                myButton.getWidth(),  
                                myButton.getHeight() * 3 + 5);  
      
                        ColorDrawable cd = new ColorDrawable(-0000);  
                        pop.setBackgroundDrawable(cd);  
                        // pop.showAsDropDown(v);  
      
                        pop.update();  
                        pop.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);  
                        pop.setTouchable(true); // 设置popupwindow可点击  
                        pop.setOutsideTouchable(true);  // 设置popupwindow外部可点击  
                        pop.setFocusable(true); //获取焦点  
                        /*设置popupwindow的位置*/  
                        pop.showAtLocation(layout,  
                                (Gravity.BOTTOM - myButton.getHeight())  
                                        | Gravity.LEFT, 0, 2 * myButton.getHeight());  
                        state = 1;  
                        pop.setTouchInterceptor(new View.OnTouchListener() {  
                            @Override  
                            public boolean onTouch(View v, MotionEvent event) {  
                                /****   如果点击了popupwindow的外部,popupwindow也会消失 ****/  
                                if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {  
                                    pop.dismiss();  
                                    return true;   
                                }  
                                return false;  
                            }  
      
                        });  
    

      由于手机分辨率不同,设置popwindow的宽度和高度时,如果给定数字,那么可能会在模拟器和手机上产生不同的效果。因此可以采用dip与px转换,也可以先获取手机的屏幕宽度和高度,根据宽度和高度进行设置。

    public class DensityUtil {  
      
        /** 
         * 根据手机的分辨率从 dp 的单位 转成为 px(像素) 
         */  
        public static int dip2px(Context context, float dpValue) {  
            final float scale = context.getResources().getDisplayMetrics().density;  
            return (int) (dpValue * scale + 0.5f);  
        }  
      
        /** 
         * 根据手机的分辨率从 px(像素) 的单位 转成为 dp 
         */  
        public static int px2dip(Context context, float pxValue) {  
            final float scale = context.getResources().getDisplayMetrics().density;  
            return (int) (pxValue / scale + 0.5f);  
        }  
    }  
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
     
    //  mPopupWindow = new PopupWindow(popupLayout,metrics.widthPixels/3,+metrics.heightPixels/2);//采用手机宽度和高度进行设置
        mPopupWindow = new PopupWindow(popupLayout,DensityUtil.dip2px(this, 150), DensityUtil.dip2px(this, 200));//通过类进行转换
    半透明弹出框PopUpWindow
    http://www.apkbus.com/android-2474-1-1.html
    PopUpWindow实现半透明弹出框关键点:
    布局文件 最外层设置为全屏 背景颜色为半透明
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
       android:layout_width="fill_parent"
        android:layout_height="fill_parent"
       android:background="@color/translucent"
        android:gravity="center"
        android:orientation="vertical"
        >
    .......
            <ListView
                android:id="@+id/qianghaoqi_diary_pop_list"
                android:divider="@null"
                android:scrollingCache="false"
                android:fadingEdge="none"
                android:scrollbarThumbVertical="@drawable/game_blade_qianghaoqi_listview_scrollbar"
                android:layout_marginBottom="@dimen/dip5"
                android:layout_marginLeft="@dimen/dip5"
               android:layout_marginRight="@dimen/dip10"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:listSelector="@null"
                android:paddingLeft="15.0dip"
               />
    .........
    </RelativeLayout>
    new一个全屏的PopUpWindow
    //必须为true,可以获取焦点
    mPopWin = new PopupWindow(aPopView, LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT,true);
    //mPopWin.setHeight(450);//设置PopupWindow高度
    //必须设置。改变弹出窗口的背景,当然也可以设置为NULL。
    mPopWin.setBackgroundDrawable(mActivity.getResources().getDrawable(R.drawable.game_blade_qianghaoqi_transparent_bg));
    mPopWin.showAtLocation(aParentView,Gravity.CENTER, 0, 0);
    //如果窗口已经显示过,更改此值只能在下一次显示时起作用,或者调用update()
    mPopWin.update();
    如果PopUpWindow内的布局会夺取焦点(如示例ListView),注意代码
    mListView.requestFocus();
    // 焦点到了listView上,所以需要监听此处的键盘事件。否则会出现不响应键盘事件的情况
    mListView.setOnKeyListener(new OnKeyListener() {
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
    if (keyCode ==  KeyEvent.KEYCODE_BACK) {
    closePopWin();
    }
    return true;
    }
    });
    关闭PopUpWindow
    private void closePopWin(){
    if (mPopWin != null && mPopWin.isShowing()) {
    mPopWin.dismiss();
    }
    }
    PopUpWindow一般应用
    mPopWin = new PopupWindow(mPopView, LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
    mPopWin.setBackgroundDrawable(mActivity.getResources().getDrawable(R.drawable.game_blade_qianghaoqi_transparent_bg));
    mPopWin.setOutsideTouchable(true);
    mPopWin.setFocusable(true);
    mPopWin.showAsDropDown(aParentView,0,-15);
    mPopWin.update();
    
    0 热度|全文链接
    #PopWin#半透明
     
    Android之PopWindow
     
    1.设置半透明主题
    2.设置window的alpha值
    //                 WindowManager.LayoutParams lp =getWindow().getAttributes();
    //          lp.alpha =0.5f; //0.0-1.0
    //         getWindow().setAttributes(lp);
    
    发现这两种都不能满足要求,起码的颜色就不太对。想做好点,做成类似alertDialog的样子,带边框,弹出窗口带动画效果,之后背景置灰,那多帅。
    看到那个仿uc浏览器的源码,是用alertdialog做的,达到那种效果,加点动画就行了。下图是从那个ucweb源码里面弄出来的。
    
    
          上面的代码就不贴了,我上传的项目文件里面也有。
           下面是弹出popupwindow的图片,第一张是动画中,第二张是完全弹出的:
    
    
    
      
    
           弹出popwindow的代码如下,比较乱,多包涵:
    
    popupWindow = new PopupWindow(menuView,LayoutParams.FILL_PARENT,
                           LayoutParams.FILL_PARENT,true);
    popupWindow.showAtLocation(findViewById(R.id.parent),Gravity.CENTER
                           |Gravity.CENTER, 0, 0);
                popupWindow.setAnimationStyle(R.style.PopupAnimation);
                 //加上下面两行可以用back键关闭popupwindow,否则必须调用dismiss();
                ColorDrawable dw = new ColorDrawable(-00000);
                popupWindow.setBackgroundDrawable(dw);
                popupWindow.update();
    
    下面是实现步骤:  
    1。背景置灰:
        popupWindow =new PopupWindow(menuView,LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT, true);
        第二三个参数必须是LayoutParams.FILL_PARENT,这样才能填充整个屏幕,达到背景置灰的目的。
        整个popupwindow里面是一个GridView,图片什么的也是用的那个仿UC浏览器界面项目的,在此谢谢了。
        关键的东西都在xml里面。
        
    <?xml version="1.0"encoding="utf-8"?>
    <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
             android:orientation="vertical"android:layout_width="fill_parent"
             android:gravity="center"android:layout_height="fill_parent"
             android:layout_gravity="center"android:background="#b0000000" >
           <LinearLayoutandroid:orientation="vertical"
                  android:layout_width="wrap_content"android:gravity="center"
                  android:layout_height="wrap_content"android:layout_gravity="center"
                  android:background="@drawable/downbutton_corner">
                 <GridViewandroid:id="@+id/gridview"android:layout_width="wrap_content"
                        android:layout_height="wrap_content"android:numColumns="4"
                        android:verticalSpacing="5dip"android:horizontalSpacing="5dip"
                        android:stretchMode="columnWidth"android:gravity="center"
                        android:layout_gravity="center"/></LinearLayout></LinearLayout>
    
    第一个linearlayout里面的android:background="#b0000000",就是全屏背景,网上搜的好多半透明都是“#e0000000”,我觉得那颜色太深,“#b0000000”更合适。
    第二个linearlayout是popupwind的背景,里面的android:background="@drawable/downbutton_corner"是关键,边框,圆角都是里面定义的。
    
    2。popupwindow的边框,圆角背景。downbutton_corne.xml
    <shapexmlns:android="http://schemas.android.com/apk/res/android"
           android:shape="rectangle">
           <gradientandroid:startColor="#c0000000"android:endColor="#c0000000"
                android:angle="90" /><!--背景颜色渐变-->
           <strokeandroid:dashWidth="2dp" android:dashGap="2dp"
                android:width="2dp"android:color="#FF00ff00"></stroke>
           <!--描边-->
           <cornersandroid:bottomRightRadius="5dp"
                android:bottomLeftRadius="5dp"android:topLeftRadius="5dp"
                android:topRightRadius="5dp"/><!--设置圆角-->
    </shape>
    
    这个涉及到shape画图,要是不懂的话。网上很多资料,搜一下就是了。我博客里面也有,http://blog.csdn.net/ymdcr/archive/2010/12/01/6048256.aspx
    <gradient android:startColor="#c0000000"android:endColor="#c0000000" android:angle="90"/><!--背景颜色渐变 -->
    我就设置了一个固定的颜色"#c0000000"。android:angle="90"这个是设置颜色渐变方向,从上到下啊,从左到右啊,貌似只能90的倍数,也只有四个方向嘛。
    <stroke></stroke>,边框就是这个实现的。
    dashWidth指的是边线的宽度 dashGap 指的是每条线之间的间距,(因为是边线是很多小横线组成的)。
    
    3。淡入淡出动画
    popupWindow.setAnimationStyle(R.style.PopupAnimation);
    这条代码是设置style的,动画文件就是在style文件里面引入的。下面是淡入的动画,动画教程网上也很多。淡出的动画就这些参数值交换位置就是了。android:duration这个是持续时间,为了截图,我把它弄成5秒了。
    <setxmlns:android="http://schemas.android.com/apk/res/android">
           <scaleandroid:fromXScale="0.6" android:toXScale="1.0"
                android:fromYScale="0.6" android:toYScale="1.0"android:pivotX="50%"
                android:pivotY="50%" android:duration="5000"/>
           <alphaandroid:interpolator="@android:anim/decelerate_interpolator"
                android:fromAlpha="0.0" android:toAlpha="1.0"android:duration="5000" />
    </set>
    复制代码
    
    大概就是这些了。
    
    还有一个关键的问题。弹出pop之后,back键无效了,必须在pop里面设置事件dismiss掉。下面是问题的描述,哪位解决了,告诉我一下,谢谢。我的邮箱:
    问题解决了,是因为没设置背景的原因。  
    popupWindow.setBackgroundDrawable(new BitmapDrawable());
    //把这一行放在showAtLocation前面就行了,以前是放在后面的,粗心了。
    popupWindow.showAtLocation(findViewById(R.id.parent),Gravity.CENTER
                 |Gravity.CENTER, 0,0);  
    网上也有很多人说,弹出pop之后,不响应键盘事件了,这个其实是焦点在pop里面的view去了。
    以这个为例,焦点就在gridview上面去了。28楼的兄弟提示的,谢了。
    在gridview加上setOnKeyListener,就能解决。
    menuGrid.setOnKeyListener(newOnKeyListener() {
            @Override
             publicboolean onKey(View v, int keyCode, KeyEvent event){
                switch(keyCode) {
                caseKeyEvent.KEYCODE_MENU:
                  if(popupWindow != null &&popupwindows.isShowing()) {
                    popupWindow.dismiss();
                    System.out.println("menuGridfdsfdsfdfd");
                  }
                  break;
               }
            
                returntrue;
            }
          });
    
    
    ---------------------------------------------------------------------------------
    使用PopupWindow来做自定义menu,往PopupWindow增加一个子View,子View的布局就是menu的布局。
    出现和退出的动画:可以给PopUpWindow或它的子view添加。
    网上所有用PopupWindow做的menu有个共同特点:就是点击menu键出现PopupWindow,然后再点击menu键无法使PopupWindow退出/dismiss()。
    当给PopupWindow设置了setFocusable(true),menu显示后,点击menu其他任何地方,menu都会消失,但是这时候按钮的点击事件其实是不响应的。同时只响应键盘的返回键,其他按键均不响应,比如点击menu键,没有任何反应。
    要解决这个问题很简单,就是给PopupWindow的子View设置下面的代码:
    [java] view plaincopy 
    //sub_view 是PopupWindow的子View  
    sub_view.setFocusableInTouchMode(true);  
    sub_view.setOnKeyListener(new OnKeyListener() {  
        @Override  
        public boolean onKey(View v, int keyCode, KeyEvent event) {  
            // TODO Auto-generated method stub  
            if ((keyCode == KeyEvent.KEYCODE_MENU)&&(mPopupWindow.isShowing())) {  
                mPopupWindow.dismiss();// 这里写明模拟menu的PopupWindow退出就行  
                return true;  
            }  
            return false;  
        }  
    });  
    
     记住,一定要给PopupWindow设置setFocusable(true),要不然点击menu其他地方以及返回键,menu都不会退出。且这时候是响应PopupWindow的parent的menu事件的。
    下面阐述为什么这么写之后,当PopupWindow显示后,点击menu键PopupWindow会退出的原因:
    首先得明白为什么给PopupWindow setFocusable(true)后,点击menu出现PopupWindow后再点击menu没反应的原因。
    PopupWindow初始化的时候一般都指定了在哪个View上出现,我们称这个View为parent。parent里面写了点击menu出现PopupWindow的事件,如果给PopupWindow setFocusable(true),此时屏幕的焦点在PopupWindow上面,肯定是不会响应parent的按键事件的,它只会响应PopupWindow的按键事件。
    但是PopupWindow的本质是Window,没有继承View类,自己没有onkeyDown或onkey或dispatchKey这些事件的。我刚开始试着实现这些接口,但是按键依然不响应,不知原因。因现在对按键的原理还不熟,无法阐述其原因。
    然后我想绕道而行,就是给PopupWindow的子View注册按键事件,setKeyListener,刚开始我在子View的xml设置了android:focusable=”true” 但按键事件依然不响应。。。。纠结啊纠结。。。然后没得办法,我google了所有关于PopupWindow的文章。。。最后终于被我发现。。。需要给PopupWindow的子View 设置setFocusableInTouchMode(true)。这时候按键事件就响应了。。。
     
    下面附上完整代码:
    [java] view plaincopy 
       /*必须重写,否则点击MENU无反应  为了让他不显示,下面onMenuOpened()必须返回false*/  
    @Override  
    public boolean onCreateOptionsMenu(Menu menu) {  
        menu.add("menu");// 必须创建一项  
        return super.onCreateOptionsMenu(menu);  
    }  
    /** 
     * 拦截MENU 
     */  
    @Override  
    public boolean onMenuOpened(int featureId, Menu menu) {  
        if(mPopupWindow != null){  
            if(!mPopupWindow.isShowing()){  
                /*最重要的一步:弹出显示   在指定的位置(parent)  最后两个参数 是相对于 x / y 轴的坐标*/  
                mPopupWindow.showAtLocation(findViewById(R.id.linear_menu_parent), Gravity.BOTTOM, 0, 0);  
            }  
        }  
        return false;// 返回为true 则显示系统menu  
    }  
      
         
       private void initPopuWindow(int menuViewID){  
        LayoutInflater mLayoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);  
        /*设置显示menu布局   view子VIEW*/  
        sub_view = mLayoutInflater.inflate(menuViewID, null);  
        /*第一个参数弹出显示view  后两个是窗口大小*/  
        mPopupWindow = new PopupWindow(sub_view, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);  
        /*设置背景显示*/  
        mPopupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_menu_popup));  
        /*设置触摸外面时消失*/  
        mPopupWindow.setOutsideTouchable(true);  
        /*设置系统动画*/  
        mPopupWindow.setAnimationStyle(android.R.style.Animation_Dialog);  
        mPopupWindow.update();  
        mPopupWindow.setTouchable(true);  
        /*设置点击menu以外其他地方以及返回键退出*/  
        mPopupWindow.setFocusable(true);  
          
        /** 1.解决再次点击MENU键无反应问题   
         *  2.sub_view是PopupWindow的子View 
         */  
        sub_view.setFocusableInTouchMode(true);  
        sub_view.setOnKeyListener(new OnKeyListener() {  
            @Override  
            public boolean onKey(View v, int keyCode, KeyEvent event) {  
                // TODO Auto-generated method stub  
                if ((keyCode == KeyEvent.KEYCODE_MENU)&&(mPopupWindow.isShowing())) {  
                    mPopupWindow.dismiss();// 这里写明模拟menu的PopupWindow退出就行  
                    return true;  
                }  
                return false;  
            }  
        });  
          
          
        /*监听MENU事件*/  
        menu = new View[3];  
        menu[0] = sub_view.findViewById(R.id.menu_0);  
        menu[1] = sub_view.findViewById(R.id.menu_1);  
        menu[2] = sub_view.findViewById(R.id.menu_2);  
          
        menu[0].setOnClickListener(new OnClickListener() {  
            @Override  
            public void onClick(View v) {  
                // doSomething  
                  
            }  
        });  
          
        menu[1].setOnClickListener(new OnClickListener() {  
            @Override  
            public void onClick(View v) {  
                // doSomething  
                  
            }  
        });  
          
        menu[2].setOnClickListener(new OnClickListener() {  
            @Override  
            public void onClick(View v) {  
                // doSomething  
                  
            }  
        });  
  • 相关阅读:
    链接服务器创建
    线性RAM地址非线性映射转换充分应用RAM地址空间TFT液晶驱动
    FPGA跨时钟域同步,亚稳态等
    Go常见的坑
    VSCode+PicGo+Gitee实现高效markdown图床
    友链
    linux 命令行使用codeql
    Linux 多进程服务配置 systemd
    列表中重复元素的个数
    起不出来题目了呜呜
  • 原文地址:https://www.cnblogs.com/lbangel/p/3475293.html
Copyright © 2020-2023  润新知