疯狂android上弄来的代码
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View root = this.getLayoutInflater().inflate(R.layout.popupwindow, null);
final PopupWindow popup = new PopupWindow(root,100,100);
TextView txt = (TextView) findViewById(R.id.txt);
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
popup.showAsDropDown(v);
//popup.showAtLocation(findViewById(R.id.btn), Gravity.CENTER_HORIZONTAL, 0, 0);
//popup.showAtLocation(findViewById(R.id.btn), Gravity.TOP, 0, 0);
}
});
root.findViewById(R.id.txtBtn).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
popup.dismiss();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
popupwindow的显示方法:showasdropdown()和showatlocation(),两种选一种就能正常显示,要关闭时只要调用dismiss()方法好了。
showAsDropDown(View anchor),这里的参数是作为popupwindow位置参考用的。也就是说,设置的popupwindow在这个anchor的下面。
而另一种方法showAtLocation(View parent, int gravity, int x, int y),第一个参数其实是随便任何一个view都可以...他会调用自身方法showAtLocation(IBinder token, int gravity, int x, int y),而parent呢只要能调用View下的public IBinder getWindowToken()方法得到一个IBinder的实例就好了。第二个是对齐方式,第三、四个是坐标偏移量。
因为今天不小心把第一个参数打错了,还得到了原本想要的结果,就蛋疼了一下,没想到传什么进去都是可以的...哦no!好像其他类也有类似的情况,之前竟然都没注意。学习之!!
嗯,popupwindow还需要设置得到自己的view。方法是
View root = this.getLayoutInflater().inflate(R.layout.popupwindow, null);
final PopupWindow popup = new PopupWindow(root,100,100);
又来了,getLayoutInflater()!得到后调用它下面的inflate方法构造出一个view来让popupwindow加载。
好样的!我在他的源码里面没有找到能输入xml文件作参数自己设定的,为毛不给个方便绿色通道让我少点事情呢真是...
我原来写的地方点击打开链接