1、首先要創建兩個xml文件,在main.xml中創建一個button,代碼如下
<?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: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();
}
}
}