1、Activity
public class MainActivity extends Activity {
private Button btn, a;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LayoutInflater inflater = LayoutInflater.from(this);
// 引入窗口配置文件
View view = inflater.inflate(R.layout.popupwindow, null);
a = (Button) view.findViewById(R.id.a);
a.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
a.setText("改变popup");
}
});
// 创建PopupWindow对象
final PopupWindow pop = new PopupWindow(view,
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, false);
// 控件
Button btn = (Button) findViewById(R.id.btn);
// 需要设置一下此参数,点击外边可消失
pop.setBackgroundDrawable(new BitmapDrawable());
// 设置点击窗口外边窗口消失
pop.setOutsideTouchable(true);
// 设置此参数获得焦点,否则无法点击
pop.setFocusable(true);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (pop.isShowing()) {
// 隐藏窗口,如果设置了点击窗口外小时即不需要此方式隐藏
pop.dismiss();
} else {
// 显示窗口
pop.showAsDropDown(v);
}
}
});
}
2、main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world"
tools:context=".MainActivity" />
</RelativeLayout>
3、popupwindow.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#ffff00">
<Button
android:id="@+id/a"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="AAAAA" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BBBBB" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CCCCC" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DDDDD" />
</LinearLayout>
重点1、<item name="android:windowBackground">@android:color/transparent</item>窗口背景色
重点2、<item name="android:windowFrame">@null</item>Dialog的windowFrame框为无
重点4、<item name="android:windowIsFloating">true</item>是否浮现在activity之上
重点5、<item name="android:windowIsTranslucent">true</item>窗口是否半透明——是(与第一条配合使用)
重点6、<item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>窗口弹出效果
重点7、<item name="android:backgroundDimEnabled">true</item> 是否允许背景模糊
重点8、<item name="android:windowContentOverlay">@null</item>这个不设置的话,可能会出现边框黑线