popupwindow实现其实很简单,就是实例化popo加载设置布局添加popo的一些属性就可以实现。
先是popup的XML布局。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="#000000"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button android:id="@+id/popupBtn"
android:layout_marginTop="20dp"
android:text="测试按钮"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView android:text="好好学习 天天向上"
android:layout_width="match_parent"
android:gravity="center"
android:textSize="20dp"
android:layout_marginTop="20dp"
android:layout_height="wrap_content"/>
</LinearLayout>
然后在看java。。。
package com.anan.PoppupWindowDemo;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.Toast;
public class MainActivity extends Activity {
/**
* Called when the activity is first created.
*/
private Button showPopupBtn;
private PopupWindow mPopupWindow;
private Context context;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context = this;
initPopup();
initView();
}
private void initView() {
showPopupBtn = (Button) findViewById(R.id.ShowPopup);
showPopupBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mPopupWindow.isShowing()) {
mPopupWindow.dismiss();
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.alpha = 1.0f; //0.0-1.0
getWindow().setAttributes(lp);
} else {
//这里后面两个参数是设置popup出现的位置的 默认是在pop下面
mPopupWindow.showAsDropDown(v, 0, 10);
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.alpha = 0.8f; //0.0-1.0
getWindow().setAttributes(lp);
}
}
});
}
/**
* pop中的按钮
*
* @param savedInstanceState
*/
private Button textBtn;
private void initPopup() {
View view = LayoutInflater.from(context).inflate(R.layout.popup_xml, null);
// 实例化popup 设置视图 以及大小 popup的大小之能在这里控制 xml中是不能改变大小的
mPopupWindow = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//设置点击视图外关闭popup
mPopupWindow.setOutsideTouchable(true);
//设置入场动画
textBtn = (Button) view.findViewById(R.id.popupBtn);
textBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mPopupWindow.dismiss();
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.alpha = 1.0f; //0.0-1.0
getWindow().setAttributes(lp);
Toast.makeText(context, "点击了按钮", 1000).show();
}
});
}
}
文章中都有注释。