PopupWindow

来源:互联网 发布:java 单引号 转义 编辑:程序博客网 时间:2024/04/30 15:42

弹窗控件,可定义其尺寸、弹出位置、内容等;

Activiy代码:
public class PopupWindowTest{

    private void ivBtn;
    private LinearLayout llContent;
    private int n;
    private PopupWindow window;

    public void onCreate(Bundle savedInstance){
        super.onCreate(savedInstance);
        setContentView(R.layout.main);

        ivBtn=(ImageView)findViewById(R.id.iv_btn);
        llContent=(LinearLayout)findViewById(R.id.ll_content);

        ivBtn.setOnClickListener(new OnClickListener(){
            n++;
            if(n%2==1){
                popupWindow();
            }else{
                window.dismiss();
            }
        });
    }

    private void popupWindow(){
        
window=new PopupWindow(); 
        
TextView contentView=LayoutInflater.from(this).inflate(R.layout.popup_content); 

        window.setWidth(200);
        window.setHeight(80);
        window.setContentView(contentView);
        window.setAnimationStyle(R.style.AnimationFade);
        window.setBackgroundDrawable(new BitmapDrawable());//没有这一句,则window会独占焦点,导致其它控件失灵
        window.setFocusable(true);
        window.setOutsideTouchable(true);
        //锚点依附在llContent的右下角,左上方向各偏移10
        
window.showAtLocation(llContent,Gravity.RIGHT|Gravity.BOTTOM,10,10);
    }


动画资源文件:res/values/styles.xml
<?xml version="1.0" encoding="utf-8"?> 
<resources xmlns:android="http://schemas.android.com/apk/res/android"> 
    <style name="AnimationFade">
        <item android:windowEnterAnimation>@android:anim/fade_in</item>
        
<item android:windowExitAnimation>@android:anim/fade_out</item> 
    </style>
</resources> 
0 0