0

我想在點擊按鈕時從我的PlaceHodler類中擴展Fragment來顯示一個彈出窗口。對於一個測試,我寫了這個代碼真的有效,但我想這很荒謬(使用Button對象作爲父視圖,等等......我找不到另一種方法來使它工作......)。請看這段代碼,並告訴我如何改進它。請不要評價我,因爲我是編程初學者。從片段顯示彈出窗口

我的代碼:

public static class PlaceholderFragment extends Fragment { 

    public PlaceholderFragment() { 
    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) { 
     View rootView = inflater.inflate(R.layout.fragment_main, container, false); 
     final Button button1 = (Button)rootView.findViewById(R.id.button1); 
     button1.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       Log.i("ilog", "onClick() works"); 
       PopupWindow pw = new PopupWindow(getActivity()); 
       TextView tv = new TextView(getActivity()); 
       LayoutParams linearparams1 = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
       tv.setLayoutParams(linearparams1); 
       tv.setText("Testing"); 
       pw.setContentView(tv); 
       pw.setWidth(400); 
       pw.setHeight(180); 
       pw.showAtLocation(button1, Gravity.CENTER_HORIZONTAL, 25, 25); 
       pw.update(); 
      } 
     }); 
     return rootView; 
    } 
} 
+0

有一點需要注意的是,你的按鈕不一定是最終的。你可以使用「view」作爲傳遞給你的onClick()方法。也就是說,你可以使用任何你可以分配OnClickListener的東西。作爲一個實驗,我使用了TextView的代碼。然而,完美的工作,關於解僱窗戶的想法? –

回答

0

你必須做的是要做到這一點正確的方式之一。 但使用本指南,以作出正確的良好的編程

guide

+0

這是一個對話框,我問的是一個彈出窗口:] – Salivan

2

popwindow在片段和活動幾乎是相同的,除了他們,你得到contrext,這種活性,片段getActivity()

這裏代碼以創建popWindow

View popupView = LayoutInflater.from(getActivity()).inflate(R.layout.popup_layout, null); 
    final PopupWindow popupWindow = new PopupWindow(popupView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT); 

// define your view here that found in popup_layout 
// for example let consider you have a button 

Button btn = (Button) popupView.findViewById(R.id.button); 

// finally show up your popwindow 
popupWindow.showAsDropDown(popupView, 0, 0); 

參考PopupWindow