PopupWindow是一种简便的弹出界面,常用的场合是点击按钮之后,会在按钮下方弹出一个界面,界面是自定义的,与一般的对话框不同,PopupWindow弹出的初始位置默认是在显示PopupWindow控件的下方。
以下是我自定义的一个PopupWindow,好处就是把PopupWindow相关的代码都集中到一个类里面,方便复用
public class MyPopupWindow { private Context mContext; private PopupWindow mPopupWindow; private View rootView; public TextView test; public MyPopupWindow(Context context) { mContext = context; rootView = LayoutInflater.from(mContext).inflate( R.layout.popup_window_layout, null); // 初始化 mPopupWindow=new PopupWindow(rootView,LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); //设置动画样式 mPopupWindow.setAnimationStyle(R.style.AnimationPreview); //设置点击空白处会消失 mPopupWindow.setTouchable(true); mPopupWindow.setOutsideTouchable(true); mPopupWindow.setBackgroundDrawable(new BitmapDrawable(mContext.getResources(), (Bitmap) null)); initViews(); } private void initViews() { // TODO Auto-generated method stub test=(TextView) rootView.findViewById(R.id.tv_pop); } //显示PopupWindow public void show(View v) { // TODO Auto-generated method stub //可以设置偏移量mPopupWindow.showAsDropDown(v, xoff, yoff); mPopupWindow.showAsDropDown(v); } //关闭PopupWindow public void close(){ mPopupWindow.dismiss(); } }
PopupWindow布局文件,简单起见只添加一个TextView
<?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:orientation="vertical" > <TextView android:id="@+id/tv_pop" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
使用:
public class MainActivity extends Activity implements OnClickListener{ private MyPopupWindow myPopupWindow; private Button btn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn = (Button)findViewById(R.id.btn); btn.setOnClickListener(this); //初始化我的PopupWindow myPopupWindow = new MyPopupWindow(mContext); } @Override public void onClick(View v) { if (v == btn) { myPopupWindow.test.setText("测试PopupWindow"); myPopupWindow.show(v); } } }
原文:http://my.oschina.net/carbenson/blog/526563