2013-08-27 46 views
18

我想使某個東西像一個彈出窗口,當點擊一個片段中的視圖時會出現。我想要這個彈出式窗口或其他任何東西,不要讓片段變暗,就像Dialog Fragment一樣。 而且我還希望彈出窗口位於視圖被點擊的位置。 如果它有自己的活動和佈局,那麼它會很好,所以我可以在其中進行一些自定義更改。 你能否告訴我一些示例代碼?彈出窗口來顯示片段中的一些東西

回答

37

以下應根據您的規格工作完美。從內部分配給視圖的OnClickListeneronClick(View v)調用此方法:

public void showPopup(View anchorView) { 

    View popupView = getLayoutInflater().inflate(R.layout.popup_layout, null); 

    PopupWindow popupWindow = new PopupWindow(popupView, 
          LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 

    // Example: If you have a TextView inside `popup_layout.xml`  
    TextView tv = (TextView) popupView.findViewById(R.id.tv); 

    tv.setText(....); 

    // Initialize more widgets from `popup_layout.xml` 
    .... 
    .... 

    // If the PopupWindow should be focusable 
    popupWindow.setFocusable(true); 

    // If you need the PopupWindow to dismiss when when touched outside 
    popupWindow.setBackgroundDrawable(new ColorDrawable()); 

    int location[] = new int[2]; 

    // Get the View's(the one that was clicked in the Fragment) location 
    anchorView.getLocationOnScreen(location); 

    // Using location, the PopupWindow will be displayed right under anchorView 
    popupWindow.showAtLocation(anchorView, Gravity.NO_GRAVITY, 
            location[0], location[1] + anchorView.getHeight()); 

} 

的意見應該解釋不夠好。 anchorView是從onClick(View v)開始的v

+0

真棒,迄今爲止工作,但我如何使它有一個邊界或什麼? –

+1

@БориславМинчев好吧,將整個'popup'佈局放置在黑色背景的'FrameLayout'中。將'popup'佈局的背景設置爲白色並給它一個'2dp'的邊距。 – Vikram

+0

太複雜了:D我用帶有框架的背景圖片做了它,並且內部顏色透明度爲70%。無論如何,上面的答案是我想要的謝謝你 –