android PopupWindow 的简单使用

来源:互联网 发布:sql验证身份证号码 编辑:程序博客网 时间:2024/05/22 08:11

简单的介绍下 Android PopupWindwo的使用。因为用到了,所以做个记录。

Here we go!

Android的对话框有两种:PopupWindow和AlertDialog。它们的不同点在于:

  • AlertDialog的位置固定,而PopupWindow的位置可以随意
  • AlertDialog是非阻塞线程的,而PopupWindow是阻塞线程的

PopupWindow的位置按照有无偏移分,可以分为偏移和无偏移两种;按照参照物的不同,可以分为相对于某个控件(Anchor锚)和相对于父控件。具体如下

  • showAsDropDown(View anchor):相对某个控件的位置(正左下方),无偏移
  • showAsDropDown(View anchor, int xoff, int yoff):相对某个控件的位置,有偏移
  • showAtLocation(View parent, int gravity, int x, int y):相对于父控件的位置(例如正中央Gravity.CENTER,下方Gravity.BOTTOM等),可以设置偏移或无偏移
 大体介绍了下,下面看段代码,很简单。

这是我程序的一段代码
private void showPopupZuliaoWindow(View parent){Log.d(TAG2, "popZuliaoWindow ==--------");if (popZuliaoWindow == null) {//如果popZuliaoWindow 未实例化,执行下面代码Log.d(TAG2, "popZuliaoWindow!=null---init-----");LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);                //get 你要弹出的画面的layout文件View view = layoutInflater.inflate(R.layout.op_other_zuliao_speed_type, null);
                        //实例化layout中的控件tv_other_zuliao=(TextView)view.findViewById(R.id.tv_other_zuoliao);
                        //我在textView的左边加了一张图片,这里实例化了Drawable 的对象drawableZuliao= getResources().getDrawable(R.drawable.op_other_zuliao_rouhe);
                        //这里是实例化了popzuliaowindow,view 是你要弹出的画面,186和66
                         //这个view的高和宽。popZuliaoWindow = new PopupWindow(view,186, 66);
                        //设置popupzuliaowindow的背景,这句是必须要有的popZuliaoWindow.setBackgroundDrawable(new ColorDrawable(android.R.color.white));
                       //触摸屏幕的其他地方,popzuliaowindow消失popZuliaoWindow.setOutsideTouchable(true);}//这句就是显示你的popupwindow了,这里的parent 是我传入的一个button对象,所以弹出的画面就在这个
                //button的正上方-2的位置,204是屏幕上的x轴的位置。popZuliaoWindow.showAsDropDown(parent, -2, 204);

好了,一个简单的popupwindow就实现了。
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="@android:color/white"    android:orientation="horizontal" >    <TextView         android:id="@+id/tv_other_zuoliao"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:gravity="center"        android:drawableLeft="@drawable/op_other_zuliao_rouhe"        android:paddingLeft="7dp"        android:text="@string/soft"        android:clickable="true"        android:textColor="#000"        android:textSize="18sp"        />    </LinearLayout>




最后感谢一下  智慧云端日记 这位博友,这里的部分内容参考了他的博文。
0 0
原创粉丝点击