|
1、首先要创建两个xml文件,在main.xml中创建一个button,代码如下
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
androidrientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/layout" >
<Button android:text="Button" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout>
在popup.xml中创建几个textView,代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip" >
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/fenxiang"
android:id="@+id/tv_fenxiang"
android:textColor="#000000"
android:textSize="30sp" />
<ImageView android:layout_width="fill_parent"
android:layout_height="1dip"
android:background="@drawable/imv_line" />
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/jubao"
android:id="@+id/tv_jubao"
android:textColor="#000000"
android:textSize="30sp" />
<ImageView android:layout_width="fill_parent"
android:layout_height="1dip"
android:background="@drawable/imv_line" />
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/cancel"
android:id="@+id/tv_cancel"
android:textColor="#000000"
android:textSize="30sp" />
</LinearLayout>
2、在ApiDemos这个Activity中代码
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
getPopupWindow();
popup.showAtLocation(findViewById(R.id.layout),Gravity.BOTTOM, 0, -70);
//popup.showAsDropDown(findViewById(R.id.layout), 20, -220);
//popup.showAsDropDown(findViewById(R.id.layout));
}
});
}
/** 创建PopupWindow */
protected void initPopuptWindow() {
View popupWindow_view = getLayoutInflater().inflate(R.layout.popup, null,false); //获取自定义布局文件popup.xml的视图
popup = new PopupWindow(popupWindow_view, 260, 160, true);//创建PopupWindow实例
tv_fenxiang = (TextView)popupWindow_view.findViewById(R.id.tv_fenxiang);//dialog.xml视图里面的控件
tv_jubao = (TextView)popupWindow_view.findViewById(R.id.tv_jubao);//dialog.xml视图里面的控件
tv_cancel = (TextView)popupWindow_view.findViewById(R.id.tv_cancel);//dialog.xml视图里面的控件
popup.setBackgroundDrawable(getResources().getDrawable(R.drawable.panel_bg));
popup.setFocusable(true);// menu菜单获得焦点 如果没有获得焦点menu菜单中的控件事件无法响应
popup.update();
/** 获取PopupWindow实例 */
private void getPopupWindow() {
if(null != popup) {
popup.dismiss();
return;
}else {
initPopuptWindow();
}
}
} |
|