安卓弹出窗口案例

一.弹出窗体

1.弹出窗体一定注意关闭
2.弹出窗体要播放动画,必须有背景资源

二.源代码

MainActivity

package com.itheima62.popupwindowdemo;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.PopupWindow;
import android.widget.RelativeLayout.LayoutParams;

public class MainActivity extends Activity {

	private PopupWindow pw;
	private AlphaAnimation aa;
	private View contentView;
	private ScaleAnimation sa;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initPopup();
	}
	
	/**
	 * 初始化弹出窗体
	 */
	private void initPopup() {
		contentView = View.inflate(getApplicationContext(), R.layout.popup, null);

        pw = new PopupWindow(contentView , -2, -2);
		
       sa = new ScaleAnimation(
    		   1, 1, 
    		   0, 1, 
    		   Animation.RELATIVE_TO_SELF, 0.5f, 
    		   Animation.RELATIVE_TO_SELF, 0f );
       sa.setDuration(1000);
        
        
		
	}

	/**
	 * 弹出窗体
	 * @param v
	 */
	public void popupWindow(View v){
		if ( pw != null && pw.isShowing()) {
			pw.dismiss();
		} else {
			int[] location = new int[2];
			/**
			 * 1,父组件
			 * 2,对齐方式
			 * 3, x坐标
			 * 4,y坐标
			 */
			v.getLocationInWindow(location );
			System.out.println("x:" + location[0] + ",y:" + location[1]);
			//设置弹出窗体的背景
			pw.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
			contentView.startAnimation(sa);
			pw.showAtLocation(v, Gravity.LEFT | Gravity.TOP, location[0] + v.getWidth(), location[1] + v.getHeight());
			
		}
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		if (pw != null && pw.isShowing()) {
			pw.dismiss();
			pw = null;
		}
		super.onDestroy();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

layout

activity.xml


    
popup.xml



    

    

    

AndroidManifest.xml




    

    
        
            
                

                
            
        
    


strings.xml




    PopupWindowDemo
    Settings
    Hello world!


关注问我技术公众号,加小问,拉您入技术交流群:
安卓弹出窗口案例_第1张图片

你可能感兴趣的:(安卓)