两布局,一个当前布局页面和一个点击展示布局页面,主程序代码:
public class MainActivity extends Activity { private PopupWindow pop; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.test); //将layout的xml布局文件实例化为View类对象 LayoutInflater inflater =LayoutInflater.from(this); View view =inflater.inflate(R.layout.mypop, null); //创建PopupWindow,参数为显示对象,宽,高 final PopupWindow pop =new PopupWindow(view, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); //PopupWindow的设置 pop.setBackgroundDrawable(new BitmapDrawable()); //点击外边消失 pop.setOutsideTouchable(true); //设置此参数获得焦点,否则无法点击 pop.setFocusable(true); //设置文本监听事件 TextView text =(TextView) findViewById(R.id.topmenu); text.setOnClickListener(new OnClickListener(){ @Override //判断是否已经显示,点击时如显示则隐藏,隐藏则显示 public void onClick(View v) { if(pop.isShowing()){ pop.dismiss(); }else{ pop.showAsDropDown(v); } } });