2019独角兽企业重金招聘Python工程师标准>>>
PopupWindow在Android.widget包下,项目中经常会使用到PopupWindow做菜单选项, PopupWindow这个类用来实现一个弹出框,可以使用任意布局的View作为其内容,这个弹出框是悬浮在当前activity之上的。
效果图:
MainActivity.java
public class MainActivity extends Activityimplements OnClickListener {private PopupWindow mPopWindow;private View parentView;private Context context;ImageView mImageViewBar;@Overrideprotected voidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);requestWindowFeature(Window.FEATURE_NO_TITLE);setContentView(R.layout.activity_main);context = this;initView();}private void initView() {// TODOAuto-generated method stubparentView =getLayoutInflater().inflate(R.layout.activity_main,null);mImageViewBar =(ImageView) findViewById(R.id.menu);mImageViewBar.setOnClickListener(this);showPopupWindow();}private void showPopupWindow() {LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);View contentView =inflater.inflate(R.layout.popuplayout,null);mPopWindow = newPopupWindow(contentView);mPopWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);mPopWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);mPopWindow = newPopupWindow();// 设置SelectPicPopupWindow的ViewmPopWindow.setContentView(contentView);// 设置SelectPicPopupWindow弹出窗体的宽mPopWindow.setWidth(LayoutParams.WRAP_CONTENT);// 设置SelectPicPopupWindow弹出窗体的高mPopWindow.setHeight(LayoutParams.WRAP_CONTENT);// 设置SelectPicPopupWindow弹出窗体可点击mPopWindow.setFocusable(true);mPopWindow.setOutsideTouchable(true);// 刷新状态mPopWindow.update();// 实例化一个ColorDrawable颜色为半透明ColorDrawable dw = new ColorDrawable(0000000000);// 点back键和其他地方使其消失,设置了这个才能触发OnDismisslistener,设置其他控件变化等操作mPopWindow.setBackgroundDrawable(dw);contentView.findViewById(R.id.memu1).setOnClickListener(this);contentView.findViewById(R.id.memu2).setOnClickListener(this);contentView.findViewById(R.id.memu3).setOnClickListener(this);}@Overridepublic void onClick(View v) {int id =v.getId();switch (id) {case R.id.menu:mPopWindow.showAsDropDown(mImageViewBar);break;case R.id.memu1: {Toast.makeText(context,"消息", Toast.LENGTH_SHORT).show();mPopWindow.dismiss();}break;case R.id.memu2: {Toast.makeText(context,"收藏", Toast.LENGTH_SHORT).show();mPopWindow.dismiss();}break;case R.id.memu3: {Toast.makeText(context,"首页", Toast.LENGTH_SHORT).show();mPopWindow.dismiss();}break;}}@Overrideprotected void onDestroy() {// TODOAuto-generated method stubsuper.onDestroy();mPopWindow.dismiss();}}
源代码下载