使用popupwindow可以将布局文件以对话框的形式弹出
PopupWindow的位置按照有无偏移分,可以分为偏移和无偏移两种;按照参照物的不同,可以分为相对于某个控件(Anchor锚)和相对于父控件。具体如下
- showAsDropDown(View anchor):相对某个控件的位置(正左下方),无偏移
- showAsDropDown(View anchor, int xoff, int yoff):相对某个控件的位置,有偏移
- showAtLocation(View parent, int gravity, int x, int y):相对于父控件的位置(例如正中央Gravity.CENTER,下方Gravity.BOTTOM等),可以设置偏移或无偏移
Activity_Main.xml //略,需要用到的控件在下面的java代码中会注释出来
popupwindow.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#a4000000>
<ImageView
android:id="@+id/shaixuan_img2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/friends"
android:layout_centerInParent="true"
android:layout_marginTop="10dp"
/>
<ImageView
android:id="@+id/shaixuan_img1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/fujin"
android:layout_above="@id/shaixuan_img2"
android:layout_centerHorizontal="true"
/>
<ImageView
android:id="@+id/shaixuan_img3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/huoyue"
android:layout_below="@id/shaixuan_img2"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
/>
</RelativeLayout>
MainActivity.java:
package com.exam.text;
import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.PopupWindow;
public class MainActivity extends Activity implements OnClickListener{
private PopupWindow popupwindow;
private ImageView imageView1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//imageView1是MainActivity中的一个控件,它是弹出对话框的事件源
imageView1 = (ImageView) findViewById(R.id.social_mainpaper_shaixuan);
imageView1.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v==imageView1){
if(popupwindow!=null&&popupwindow.isShowing()){
popupwindow.dismiss();
}else {
initPopupWindow();
popupwindow.showAsDropDown(v, 5, 25);
}
}
}
public void initPopupWindow(){
View view3 = getLayoutInflater().inflate(R.layout.pengyouquan_shaixuan, null);
popupwindow = new PopupWindow(view3,170,180);
view3.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(popupwindow!=null&&popupwindow.isShowing()){
popupwindow.dismiss();
popupwindow=null;
return ;
}
}
});
}
}
运行结果:
运行前:
运行后: