Android PopupWindow全屏详细介绍及实例代码

 Android PopupWindow全屏

很多应用中经常可以看到弹出这种PopupWindow的效果,做了一个小demo分享一下。demo的思路是通过遍历文件,找到图片以及图片文件夹放置在PopupWindow上面。点击按钮可以弹出这个PopupWindow,这里为PopupWindow设置了动画。

PopupWindow全屏代码提要

受限需要自定义Popupwindow,这里不看Popupwindow里面要展示的内容,主要是设置Popupwindow的高度。

public class PopupwindowList extends PopupWindow {
  private int mWidth;
  private int mHeight;
  private View mContentView;
  private List<FileBean> mFileBeans;
  private ListView mListView;

  public PopupwindowList(Context context,List<FileBean> mFileBeans) {
    super(context);
    this.mFileBeans=mFileBeans;
    //计算宽度和高度
    calWidthAndHeight(context);
    setWidth(mWidth);
    setHeight(mHeight);
    mContentView= LayoutInflater.from(context).inflate(R.layout.popupwidow,null);
    //设置布局与相关属性
    setContentView(mContentView);
    setFocusable(true);
    setTouchable(true);
    setTouchable(true);
    setTouchInterceptor(new View.OnTouchListener() {
      @Override
      public boolean onTouch(View v, MotionEvent event) {
      //点击PopupWindow以外区域时PopupWindow消失
        if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
          dismiss();
        }
        return false;
      }
    });

  }

  /**
   * 设置PopupWindow的大小
   * @param context
   */
  private void calWidthAndHeight(Context context) {
    WindowManager wm= (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    DisplayMetrics metrics= new DisplayMetrics();
    wm.getDefaultDisplay().getMetrics(metrics);

    mWidth=metrics.widthPixels;
    //设置高度为全屏高度的70%
    mHeight= (int) (metrics.heightPixels*0.7);
  }
}

点击按钮弹出PopupWindow

 mButtonShowPopup.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        //点击时弹出PopupWindow,屏幕变暗
        popupwindowList.setAnimationStyle(R.style.ListphotoSelect);
        popupwindowList.showAsDropDown(mButtonShowPopup, 0, 0);
        lightoff();

      }
    });
 private void lightoff() {
    WindowManager.LayoutParams lp=getWindow().getAttributes();
    lp.alpha=0.3f;
    getWindow().setAttributes(lp);
  }

一、FileBean类保存信息

FileBean如上图PopupWindow所示,需要保存文件的路径,文件夹的名称,文件夹中文件的数量,文件夹中第一张图片的路径。基本全部为set、get方法

/**
 * this class is used to record file information like the name of the file 、the path of the file……
 *
 */
public class FileBean {
  private String mFileName;
  private String mFilePath;
  private String mFistImgPath;
  private int mPhotoCount;

  public String getmFileName() {
    return mFileName;
  }

  public void setmFileName(String mFileName) {
    this.mFileName = mFileName;
  }

  public String getmFilePath() {
    return mFilePath;
  }

  public void setmFilePath(String mFilePath) {
    this.mFilePath = mFilePath;
    int index=this.mFilePath.lastIndexOf(File.separator);
    mFileName=this.mFilePath.substring(index);
  }

  public String getmFistImgPath() {
    return mFistImgPath;
  }

  public void setmFistImgPath(String mFistImgPath) {
    this.mFistImgPath = mFistImgPath;
  }

  public int getmPhotoCount() {
    return mPhotoCount;
  }

  public void setmPhotoCount(int mPhotoCount) {
    this.mPhotoCount = mPhotoCount;
  }
}

二、PopupWidow界面设置

自定义PopupWindow,

public class PopupwindowList extends PopupWindow {
  private int mWidth;
  private int mHeight;
  private View mContentView;
  private List<FileBean> mFileBeans;
  private ListView mListView;
  //观察者模式
  public interface OnSeletedListener{
    void onselected(FileBean bean);
  }
  private OnSeletedListener listener;
  public void setOnSelecterListener(OnSeletedListener listener){
    this.listener=listener;
  }
  public PopupwindowList(Context context,List<FileBean> mFileBeans) {
    super(context);
    this.mFileBeans=mFileBeans;
    calWidthAndHeight(context);
    setWidth(mWidth);
    setHeight(mHeight);
    mContentView= LayoutInflater.from(context).inflate(R.layout.popupwidow,null);
    setContentView(mContentView);
    setFocusable(true);
    setTouchable(true);
    setTouchable(true);
    setTouchInterceptor(new View.OnTouchListener() {
      @Override
      public boolean onTouch(View v, MotionEvent event) {
      //点击PopupWindow以外区域时PopupWindow消失
        if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
          dismiss();
        }
        return false;
      }
    });
    initListView(context);
    initEvent();
  }

  private void initEvent() {

  }
  //初始化PopupWindow的listview
  private void initListView(Context context) {
    MyListViewAdapter adapter=new MyListViewAdapter(context,0,mFileBeans);
    mListView= (ListView) mContentView.findViewById(R.id.listview);
    mListView.setAdapter(adapter);
  }

  /**
   * 设置PopupWindow的大小
   * @param context
   */
  private void calWidthAndHeight(Context context) {
    WindowManager wm= (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    DisplayMetrics metrics= new DisplayMetrics();
    wm.getDefaultDisplay().getMetrics(metrics);

    mWidth=metrics.widthPixels;
    mHeight= (int) (metrics.heightPixels*0.7);
  }
}

三、点击按钮弹出PopupWindow

public class PopupWindowTest extends AppCompatActivity {
  private Button mButtonShowPopup;
  private Set<String> mFilePath;
  private List<FileBean> mFileBeans;
  PopupwindowList popupwindowList;
  private Handler mHandler=new Handler(){
    @Override
    public void handleMessage(Message msg) {
      super.handleMessage(msg);
      initPopupWindow();
    }
  };

  private void initPopupWindow() {
    popupwindowList=new PopupwindowList(this,mFileBeans);
    popupwindowList.setOnDismissListener(new PopupWindow.OnDismissListener() {
      @Override
      public void onDismiss() {
        lighton();
      }
    });

  }
    //PopupWindow消失时,使屏幕恢复正常
  private void lighton() {
    WindowManager.LayoutParams lp=getWindow().getAttributes();
    lp.alpha=1.0f;
    getWindow().setAttributes(lp);
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.popupwindowtestlayout);
    mButtonShowPopup= (Button) findViewById(R.id.button_showpopup);
    mFileBeans=new ArrayList<>();
    initData();
    initEvent();

  }

  private void initEvent() {

    mButtonShowPopup.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        //点击时弹出PopupWindow,屏幕变暗
        popupwindowList.setAnimationStyle(R.style.ListphotoSelect);
        popupwindowList.showAsDropDown(mButtonShowPopup, 0, 0);
        lightoff();

      }
    });
  }

  private void lightoff() {
    WindowManager.LayoutParams lp=getWindow().getAttributes();
    lp.alpha=0.3f;
    getWindow().setAttributes(lp);
  }
  //开启线程初始化数据,遍历文件找到所有图片文件,及其文件夹与路径进行保存。
  private void initData() {
    if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
      ToastUtils.showToast(this,"当前sdcard不用使用");
    }
    new Thread(){
      @Override
      public void run() {
        super.run();
        Uri imgsUri= MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        ContentResolver contentResolver=getContentResolver();
        Cursor cursor=contentResolver.query(imgsUri,null,MediaStore.Images.Media.MIME_TYPE + "=? or " + MediaStore.Images.Media.MIME_TYPE + "=?",new String[]{"image/jpeg","image/png"},MediaStore.Images.Media.DATA);
        mFilePath=new HashSet<>();
        while (cursor.moveToNext()){
          String path=cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
          File parentfile=new File(path).getParentFile();
          if(parentfile==null) continue;
          String filePath=parentfile.getAbsolutePath();
          FileBean fileBean=null;

          if(mFilePath.contains(filePath)){
             continue;
          }else {
            mFilePath.add(filePath);
            fileBean=new FileBean();
            fileBean.setmFilePath(filePath);
            fileBean.setmFistImgPath(path);
          }
          if(parentfile.list()==null) continue;
           int count=parentfile.list(new FilenameFilter() {
             @Override
             public boolean accept(File dir, String filename) {
               if(filename.endsWith(".jpg")||filename.endsWith(".png")||filename.endsWith(".jpeg")){

                 return true;
               }
               return false;
             }
           }).length;
          fileBean.setmPhotoCount(count);
          mFileBeans.add(fileBean);

        }

        cursor.close();
        //将mFilePath置空,发送消息,初始化PopupWindow。
        mFilePath=null;
        mHandler.sendEmptyMessage(0x110);

      }
    }.start();

  }

}

四、PopupWindow动画设置。

(1)编写弹出与消失动画

①弹出动画

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="0"
  android:toXDelta="0"
  android:fromYDelta="100%"
  android:toYDelta="0"
  android:duration="1000"></translate>
</set>

②消失动画

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
  <translate android:fromXDelta="0"
    android:toXDelta="0"
    android:fromYDelta="0"
    android:toYDelta="100%"
    android:duration="1000"></translate>
</set>

(2)设置style与调用style

①设置style

在style中进行添加

<resources>

  <!-- Base application theme. -->
  <style name="AppTheme" parent="Theme.AppCompat.Light">
    <!-- Customize your theme here. -->
  </style>
  <style name="ListphotoSelect">
    <item name="android:windowEnterAnimation">@anim/animshow</item>
    <item name="android:windowExitAnimation">@anim/animdismiss</item>
  </style>
</resources>

②调用style

为PopupWindow设置动画style

  popupwindowList.setAnimationStyle(R.style.ListphotoSelect);

备注:布局很简单不再展示。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

(0)

相关推荐

  • Android 应用的全屏和非全屏实现代码

    Android 应用的全屏和非全屏实现代码 全屏显示操作: /** * 全屏显示 */ private void setFullSreen() { WindowManager.LayoutParams params = getWindow().getAttributes(); params.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN; getWindow().setAttributes(params); getWindow().addF

  • Android编程使WebView支持HTML5 Video全屏播放的解决方法

    本文实例讲述了Android编程使WebView支持HTML5 Video全屏播放的解决方法.分享给大家供大家参考,具体如下: 1)需要在AndroidManifest.xml文件中声明需要使用HardwareAccelerate, 可以细化到Activity级别,如果不需要的View可以声明不要用加速,但是需要在代码中做,具体如下: a. 如果要声明整个应用都要加速: 复制代码 代码如下: <application ... android:hardwareAccelerated ="tr

  • Android 实现全屏显示的几种方法整理

    Android 实现全屏显示的几种方法整理 A.设置主题实现全屏 直接在AndroidManifest.xml文件中设定Activity主题为全屏模式 android:theme="@android:style/Theme.NoTitleBar.Fullscreen" B.代码实现全屏 代码实现需要分两步做,如下: 1.隐藏标题栏 requestWindowFeature(Window.FEATURE_NO_TITLE); 2.隐藏状态栏 getWindow().setFlags(Wi

  • Android UI体验之全屏沉浸式透明状态栏样式

    前言: Android 4.4之后谷歌提供了沉浸式全屏体验, 在沉浸式全屏模式下, 状态栏. 虚拟按键动态隐藏, 应用可以使用完整的屏幕空间, 按照 Google 的说法, 给用户一种 身临其境 的体验.而Android 5.0之后谷歌又提出了 ColorPalette 的概念,让开发者可以自己设定系统区域的颜色,使整个 App 的颜色风格和系统的颜色风格保持统一.今天学习总结一下如何实现Android 4.4以上全屏沉浸式透明状态栏效果.先看下预期效果: 首先现分清楚哪部分是状态栏,哪部分是导

  • Android 全屏无标题栏的三种实现方法

    一.通过Java代码 在setContentView之前执行: requestWindowFeature(Window.FEATURE_NO_TITLE);//隐藏标题栏 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);//隐藏状态栏 二.调用Android自带的Theme 直接在AndroidManifest.xml中需要全屏显

  • Android编程之界面实现全屏显示的方法(2种方法)

    本文实例讲述了Android编程之界面实现全屏显示的方法.分享给大家供大家参考,具体如下: 在开发android的应用当中,我们会遇到将一些界面设置为全屏显示的格式,有两种实现的方法.其一是在Java代码中实现,其二是在配置文件中实现. 1. 在Java代码中设置 super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); //无title getWindow().setFlags(Wind

  • Android编程实现WebView自适应全屏方法小结

    本文实例讲述了Android编程实现WebView自适应全屏的方法.分享给大家供大家参考,具体如下: 第一种: settings.setUseWideViewPort(true); settings.setLoadWithOverviewMode(true); 第二种: WebSetting settings = webView.getSettings(); settings.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN); 把所有内容放在we

  • Android全屏设置的方法总结

    Android 有两种方式可以设置全屏. 第一种方式:在protected void onCreate(Bundle savedInstanceState) 里面的this.setContentView() 之前加入以下代码 //取消标题 this.requestWindowFeature(Window.FEATURE_NO_TITLE); //取消状态栏 this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,

  • Android PopupWindow全屏详细介绍及实例代码

     Android PopupWindow全屏 很多应用中经常可以看到弹出这种PopupWindow的效果,做了一个小demo分享一下.demo的思路是通过遍历文件,找到图片以及图片文件夹放置在PopupWindow上面.点击按钮可以弹出这个PopupWindow,这里为PopupWindow设置了动画. PopupWindow全屏代码提要 受限需要自定义Popupwindow,这里不看Popupwindow里面要展示的内容,主要是设置Popupwindow的高度. public class Po

  • Android AsyncTask实现机制详细介绍及实例代码

    Android AsyncTask实现机制 示例代码: public final AsyncTask<Params, Progress, Result> execute(Params... params) { return executeOnExecutor(sDefaultExecutor, params); } public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec, Pa

  • JS 全屏和退出全屏详解及实例代码

    JS 全屏和退出全屏 js实现浏览器窗口全屏和退出全屏的功能,市面上主流浏览器如:谷歌.火狐.360等都是兼容的,不过IE低版本有点瑕疵(全屏状态下仍有底部的状态栏). 这个demo基本是够了,直接复制下面的源码另存为html文件看效果吧. <!DOCTYPE html> <html> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <

  • Android Loader详细介绍及实例代码

    一,Android装载器基本方法 装载器从android3.0开始引进.它使得在activity或fragment中异步加载数据变得简单.装载器具有如下特性: 它们对每个Activity和Fragment都有效. 他们提供了异步加载数据的能力. 它们监视数据源的一将一动并在内容改变时传送新的结果. 当由于配置改变而被重新创建后,它们自动重连到上一个加载器的游标,所以不必重新查询数据. 装载器API概述 在使用装载器时,会涉及很多类和接口们,我们在下表中对它们总结一下: Class/Interfa

  • Java Filter 过滤器详细介绍及实例代码

    Filter简介 Filter也称之为过滤器,它是Servlet技术中最实用的技术,WEB开发人员通过Filter技术,对web服务器管理的所有web资源:例如Jsp, Servlet, 静态图片文件或静态 html 文件等进行拦截,从而实现一些特殊的功能.例如实现URL级别的权限访问控制.过滤敏感词汇.压缩响应信息等一些高级功能. 它主要用于对用户请求进行预处理,也可以对HttpServletResponse 进行后处理.使用Filter 的完整流程:Filter 对用户请求进行预处理,接着将

  • AngularJS Bootstrap详细介绍及实例代码

    AngularJS Bootstrap AngularJS 的首选样式表是 Twitter Bootstrap, Twitter Bootstrap 是目前最受欢迎的前端框架. 查看 Bootstrap教程. Bootstrap 你可以在你的 AngularJS 应用中加入 Twitter Bootstrap,你可以在你的 <head>元素中添加如下代码: <link rel="stylesheet" href="//maxcdn.bootstrapcdn.

  • AngularJS 模型详细介绍及实例代码

    AngularJS ng-model 指令 ng-model 指令用于绑定应用程序数据到 HTML 控制器(input, select, textarea)的值. ng-model 指令 ng-model 指令可以将输入域的值与 AngularJS 创建的变量绑定. AngularJS 实例 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="

  • AngularJS中的Promise详细介绍及实例代码

    Angular中的Promise 在用jQuery的时候就知道 promise 是 Js异步编程模式的一种模式,但是不是很明白他跟JQuery的deferred对象有什么区别.随着公司项目的进行,要跟后台接数据了,所以决定搞定它. Promise Promise是一种模式,以同步操作的流程形式来操作异步事件,避免了层层嵌套,可以链式操作异步事件. 我们知道,在编写JavaScript异步代码时,callback是最最简单的机制,可是用这种机制的话必须牺牲控制流.异常处理和函数语义化为代价,甚至会

  • Java 线程的生命周期详细介绍及实例代码

    当线程被创建并启动之后,它既不是一启动就进入执行状态,也不是一直处于执行状态,在其生命周期中,要经过"新建(New)"."就绪(Runnable)"."运行(Running')"."阻塞(Blocked)"和"死亡(Dead)"五种状态.线程在创建之后,不可能一直霸占着CPU独立运行,需要在多个线程之间切换,所以大部分时间处于运行.阻塞之间切换.  一.线程的状态 线程的存在有几种不同的状态,如下: New

  • java 线程同步详细介绍及实例代码

    java 线程同步 概要: 为了加快代码的运行速度,我们采用了多线程的方法.并行的执行确实让代码变得更加高效,但随之而来的问题是,有很多个线程在程序中同时运行,如果它们同时的去修改一个对象,很可能会造成讹误的情况,这个时候我们需要用一种同步的机制来管理这些线程. (一)竞争条件 记得操作系统中,让我印象很深的有一张图.上面画的是一块块进程,在这些进程里面分了几个线程,所有这些线程齐刷刷统一的指向进程的资源.Java中也是如此,资源会在线程间共享而不是每个线程都有一份独立的资源.在这种共享的情况下

随机推荐