1 package com.lixu.tanchuchuangti; 2 3 import android.app.Activity; 4 import android.graphics.Color; 5 import android.os.Bundle; 6 import android.view.Gravity; 7 import android.view.LayoutInflater; 8 import android.view.View; 9 import android.view.View.OnClickListener; 10 import android.widget.Button; 11 import android.widget.PopupWindow; 12 import android.widget.TextView; 13 14 public class MainActivity extends Activity { 15 16 @Override 17 protected void onCreate(Bundle savedInstanceState) { 18 super.onCreate(savedInstanceState); 19 setContentView(R.layout.activity_main); 20 21 final Activity activity = this; 22 23 final Button button = (Button) findViewById(R.id.button1); 24 25 button.setOnClickListener(new OnClickListener() { 26 27 @Override 28 public void onClick(View v) { 29 LayoutInflater mLayoutInflater = activity.getLayoutInflater(); 30 View view = mLayoutInflater.inflate(android.R.layout.simple_list_item_1, null); 31 TextView tv = (TextView) view.findViewById(android.R.id.text1); 32 33 view.setBackgroundColor(Color.GRAY); 34 tv.setTextColor(Color.BLUE); 35 tv.setText("你好啊 !!"); 36 37 PopupWindow pw = new PopupWindow(view, 100, 100); 38 // 将弹出窗体设置在按钮之下 39 // pw.showAsDropDown(button); 40 41 // 设置背景图片 42 pw.setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.dfdf)); 43 // 这里要设置一个背景图片才能触发这个功能 44 // 点击窗体外关闭弹出窗体 45 pw.setOutsideTouchable(true); 46 // 设置弹出框居中 47 pw.showAtLocation(activity.getWindow().getDecorView(), Gravity.CENTER, 0, 0); 48 49 } 50 }); 51 } 52 53 }
运行效果图:
时间: 2024-10-06 00:12:22