安卓自定义PopWindow

1、创建自定义PopWindow
2、创建anim,弹出弹入动画,和动画Style
3、实际使用案例

1、创建自定义PopWindow

1.1 创建展示界面
在创建该类之前,先构思好需要展示的布局文件(PopWindow展示的界面)样式。
这里写图片描述
1.2 自定义创建PopWindow类

 public void initPopWindow(){
    //初始化
        //获取PopWindow()布局的view
        mView = LinearLayout.inflate(mContext, R.layout.popup_takephoto, null);
        mPopupWindow = new PopupWindow(mView,LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT,true);
        mPopupWindow.setTouchable(true);
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable(mContext.getResources(), (Bitmap )null));

        mPopupWindow.getContentView().setFocusableInTouchMode(true);
        mPopupWindow.setFocusable(true);
        mPopupWindow.setAnimationStyle(R.style.anim_menu_bottombar);
    //布局点击设置
    //如果需要对PopupWindow布局中设置点击事件,可通过布局的View获取,并设置点击事件
        mView.findViewById(R.id.popup_camera).setOnClickListener(this);
        mView.findViewById(R.id.popup_album).setOnClickListener(this);
        mView.findViewById(R.id.popup_cancel).setOnClickListener(this);

    }
//显示PopupWindow的方法
public void showAtBottom( View view){
        mPopupWindow.showAtLocation(mView, Gravity.BOTTOM, 0, 0);
        mPopupWindow.showAsDropDown(view);
    }
//隐藏PopupWindow的方法
    public void dismiss(){
        mPopupWindow.dismiss();
    }
   // 自定义布局点击事件的接口
  Public interface PopItemClickListener{
Void onClickItem(intRequestCode);
}
public void setPopItemClickListener(PopItemClickListenerpopItemClickListener){
mPopItemClickListener=popItemClickListener;
}

2、创建anim,弹出弹入动画,和动画Style

2.1创建anim
在res目录下创建anim文件夹
这里写图片描述
创建Animation动画包括弹入弹出两个动画文件。
这里写图片描述
该动画文件用到的是 平移动画:
① anim_menu_bottombar_in

<?xmlversion="1.0"encoding="utf-8"?>
<setxmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:duration="250"
android:fromYDelta="100.0%"
android:toYDelta="0.0"
/>
</set>

② anim_menu_bottombar_out

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
    android:duration="250"
    android:fromYDelta="0.0%"
    android:toYDelta="100.0"
    />
</set>

创建后的目录结构如下图所示
这里写图片描述
2.2 在Style中设置
在values/styles文件中添加创建好的动画属性。

 <style name="anim_menu_bottombar">
        <item name="android:windowEnterAnimation">@anim/anim_menu_bottombar_in</item>
        <item name="android:windowExitAnimation">@anim/anim_menu_bottombar_out</item>
    </style>

在代码中使用该style属性

mPopupWindow.setAnimationStyle(R.style.anim_menu_bottombar);

3、实际使用案例

在需要使用的时候,首先进行自定义Popwindow的初始化操作。

//初始化popwindow
mCameraPopupWindow = new CameraPopupWindow(this);
mCameraPopupWindow.initPopWindow();
mCameraPopupWindow.setPopItemClickListener(new CameraPopupWindow.PopItemClickListener(){
@Override
publicvoidonClickItem(intRequestCode){
//popwindow中item点击事件的处理
}});
//在需要显示的时候调用
mCameraPopupWindow.showAtBottom(v);

//隐藏该Popwindow
mCameraPopupWindow.dismiss();

猜你喜欢

转载自blog.csdn.net/xk7298/article/details/81604948