一个PopupWindow能显示任意的View。 PopupWindow是漂浮在其他当前Activity之上显示的容器。

demo代码如下:

public class TestPopupWindow extends Activity {
	
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        bt_disPW = (Button) findViewById(R.id.disPW);
        bt_disPW.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// display popup window
				Log.d("lxy", "at TestActivity button click event");
				
				
				LinearLayout mLayout = new LinearLayout(TestPopupWindow.this);
				TextView tv = new TextView(TestPopupWindow.this);
				tv.setTextColor(Color.BLACK);
				tv.setText("test popup window");
				mLayout.addView(tv);
				
				PopupWindow ppw = new PopupWindow(mLayout, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
				ppw.setBackgroundDrawable(new ColorDrawable(Color.GRAY));// 设置背景
				ppw.setFocusable(true);
				ppw.getBackground().setAlpha(60);
				
				ppw.showAtLocation(findViewById(R.id.disPW), Gravity.CENTER_VERTICAL, 0, 0);
			}
		});
    }
    
    private Button bt_disPW;
}


main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:background="#FF5555FF"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
    
    <Button
    android:text="DispaleyPopupWindow"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/disPW"></Button>
</LinearLayout>


 

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐