Android 弹出窗口 PopupWindow
代码如下:
package com.example.tanchuangdemo;
import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupWindow;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Activity activity = this ;
final Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LayoutInflater mInflater = activity.getLayoutInflater();
View view = mInflater.inflate(R.layout.myview, null);
ListView list = (ListView) view.findViewById(R.id.list_view);
String[] data = new String[50];
for(int i= 0;i<50;i++){
data[i] = "测试数据"+i;
}
ArrayAdapter adapter = new ArrayAdapter(activity, android.R.layout.simple_list_item_1, data);
list.setAdapter(adapter);
//创建一个popup window,指定宽高 300宽,高700
PopupWindow mpopupWindow = new PopupWindow(view, 1200, 2120);
//在popup window外面的空白处点击,即可关闭popup window。
mpopupWindow.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.alert_light_frame));
mpopupWindow.setOutsideTouchable(true);
//像Toast的show()一样显示出来。
mpopupWindow.showAtLocation(activity.getWindow().getDecorView(),Gravity.CENTER, 0, 0);
}
});
}
}
共两个布局文件,activity_main布局文件里定义一个button按钮:
<?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:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Button" />
</RelativeLayout >
<?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="@drawable/ic_launcher"
android:orientation="vertical" >
<ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
></ListView>
</LinearLayout>
运行结果,点击按钮后弹窗效果: