Android PopupWindow全屏詳細介紹及執行個體代碼_Android

來源:互聯網
上載者:User

 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);

備忘:布局很簡單不再展示。

感謝閱讀,希望能協助到大家,謝謝大家對本站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.