第一步:自定义xml文件
第二步:获取LayoutInflater对象
第三步:调用inflate()方法获取View对象
第四步:创建PopupWindow对象
第五步:调用PopupWindow的showAsDropDown或者showAsLocation方法显示对话框
activity.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="es.source.code.activity.popupwindowtest_tencentclass.MainActivity"> <Button android:id="@+id/btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="点击" android:onClick="btnClick"/> </RelativeLayout>
layout_myself_dialog.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:background="#fff" > <LinearLayout android:layout_width="match_parent" android:layout_height="40dp" android:background="#0e2438" android:gravity="center" android:orientation="horizontal" > <TextView android:text="提醒" android:textSize="18sp" android:textColor="#fff" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:orientation="vertical" android:padding="10dp" > <TextView android:text="恭喜您,验证码发送成功" android:textSize="18sp" android:textColor="#000" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:id="@+id/btn" android:text="确定" android:textColor="#fff" android:textSize="14sp" android:layout_width="66dp" android:layout_height="30dp" android:background="@drawable/bg4" android:layout_marginTop="10dp"/> </LinearLayout> </LinearLayout>
MainActivity.class
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //View view = this.getLayoutInflater().inflate(R.layout.layout_myself_dialog, null); LayoutInflater inflater = LayoutInflater.from(this); View myView = inflater.inflate(R.layout.layout_myself_dialog, null); popupWindow = new PopupWindow(myView, 600, 450); myView.findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { popupWindow.dismiss(); } }); } PopupWindow popupWindow; public void btnClick(View v) { popupWindow.showAsDropDown(v); } }