java
package com.example.learn;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.PopupWindow;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "leo";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void leoClick(View view){
View popupView=getLayoutInflater().inflate(R.layout.popup,null);
Button btn1=popupView.findViewById(R.id.btn1);
Button btn2=popupView.findViewById(R.id.btn2);
PopupWindow popupWindow=new PopupWindow(popupView, ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT,true);
popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.moon));
popupWindow.showAsDropDown(view);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e(TAG, "onClick: 你住在上海吗" );
popupWindow.dismiss();
}
});
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e(TAG, "onClick: 你住在安徽吗" );
popupWindow.dismiss();
}
});
}
}
xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<Button
android:text="弹出PopupWindow"
android:onClick="leoClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
<?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="match_parent"
android:background="@mipmap/ic_launcher"
android:orientation="vertical"
>
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#ff0000"
android:text="上海"
android:textSize="18sp"
/>
<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#02FADD"
android:text="安徽"
android:textSize="18sp"
/>
</LinearLayout>
结果图