PopupWindow是阻塞式对话框:PopupWindow弹出时,程序会等待,在PopupWindow退出前,程序一直等待,只有当我们调用了dismiss方法的后,PopupWindow退出,程序才会向下执行.
PopupWindow pw = new PopupWindow(view,width,height);
pw.setContentView(popupconten);//重新设置PopupWindow的内容
pw.setFocusable(true);//默认是false,为false时,PopupWindow没有获得焦点能力,如果这是PopupWindow的内容中有EidtText,需要输入,这是是无法输入的;只有为true的时候,PopupWindow才具有获得焦点能力,EditText才是真正的EditText。
pw.setAsDropDown(View view);//设置PopupWindow弹出的位置。
案列:主要代码:
package com.example.demo3; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import android.support.v7.app.ActionBarActivity; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.GridView; import android.widget.ListAdapter; import android.widget.PopupWindow; import android.widget.SimpleAdapter; public class MainActivity extends ActionBarActivity { PopupWindow popupWindow; View parent; private int[] images = {R.drawable.i1,R.drawable.i2,R.drawable.i3,R.drawable.i4 ,R.drawable.i5,R.drawable.i6,R.drawable.i7,R.drawable.i8}; private String[] names = {"搜索","文件管理","下载管理","全屏","网址","书签","加入书签","分享页面"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); View contentView = getLayoutInflater().inflate(R.layout.popup, null); GridView gridView = (GridView) contentView.findViewById(R.id.gridView); gridView.setAdapter(getAdapter());//为gridView 绑定数据 gridView.setOnItemClickListener(new ItemClickListener()); popupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); popupWindow.setFocusable(true); popupWindow.setBackgroundDrawable(new BitmapDrawable()); popupWindow.setAnimationStyle(R.style.animation); // parent = this.findViewById(R.layout.activity_main);(这样没有得到view) parent = getLayoutInflater().inflate(R.layout.popup, null); } private final class ItemClickListener implements OnItemClickListener{ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if(popupWindow.isShowing()){ popupWindow.dismiss();//关闭popupWindow } } } private ListAdapter getAdapter() { List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>(); for(int i=0;i<images.length;i++){ HashMap<String, Object> item = new HashMap<String, Object>(); item.put("images", images[i]); item.put("names", names[i]); data.add(item); } SimpleAdapter simpleAdapter = new SimpleAdapter(this, data, R.layout.grid_item, new String[]{"images","names"}, new int[]{R.id.imageView,R.id.textView}); return simpleAdapter; } public void openPopView(View v){ Log.d("TAG", "pop了"); popupWindow.showAtLocation(parent, Gravity.BOTTOM, 0, 0); } }
完整代码链接:http://download.csdn.net/detail/tan313/8291977