2017-10-08 89 views
0

我想在android中創建自定義popupWindow。我手邊有兩個問題 1.如何根據可用的屏幕大小放置popupwindow(左,右,上,下)。例如 彈出窗口鏈接到的按鈕 a。如果它位於左上角,它應該打開在按鈕底部 b。如果它位於屏幕的左下角,彈出應該在按鈕頂部的右側打開基於可用屏幕大小的Android PopupWindow放置

  1. 如何在彈出窗口附加到一個視圖(如一個按鈕)

回答

0

首先,你必須確定你的彈出windown的佈局。 例子:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"> 

    <Button 
     android:layout_height="wrap_content" 
     android:layout_width="wrap_content" 
     android:text="Button" 
     android:id="@+id/button"> 
    </Button> 

</LinearLayout> 

接下來,創建該處理您的彈出windown

import android.content.Context; 
import android.view.Gravity; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup.LayoutParams; 
import android.view.WindowManager; 
import android.widget.ListView; 
import android.widget.PopupWindow; 

public class PopupMenu extends PopupWindow 
{ 
    Context  m_context; 

    public PopupMenu(Context context) 
    { 
     super(context); 

     m_context = context; 

     setContentView(LayoutInflater.from(context). 
      inflate(R.layout.popup_menu, null)); 

     setHeight(WindowManager.LayoutParams.WRAP_CONTENT); 
     setWidth(WindowManager.LayoutParams.WRAP_CONTENT); 
    } 

    public void show(View anchor) 
    { 
     // you can edit display location is here 
     showAtLocation(anchor, Gravity.CENTER, 0, 0); 
    } 
} 

您可以輕鬆地使用此代碼中使用一個類:

PopupMenu popupMenu = new PopupMenu(context); 
popupMenu.show(view); 

如果你把在ListView你的PopupWindow,將寬度設置爲WRAP_CONTENT將不起作用。爲了設定PopupWindow適當的寬度,你就必須在節目添加這個()方法:

// force the popupwindow width to be the listview width 
listview.measure(
       View.MeasureSpec.UNSPECIFIED, 
       View.MeasureSpec.UNSPECIFIED) 
setWidth(listview.getMeasuredWidth()); 

我希望它可以幫助您的問題! 很高興幫助你!

+0

如何根據可用的屏幕寬度來放置popupwindow。 –