2016-05-17 18 views
0

我想在用戶單擊列表項時顯示一個popupwindow。我在我的片段的Adapter類中使用了initiatePopWindow()。我如何解決findViewByIdConfirmActivity無法解析Adapter類中的ConfirmActivity和findViewById

private void initiatePopupWindow() { 
     try { 
      //We need to get the instance of the LayoutInflater, use the context of this activity 
      LayoutInflater inflater = (LayoutInflater) ConfirmActivity.this 
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      //Inflate the view from a predefined XML layout 
      View layout = inflater.inflate(R.layout.popup_addword, 
        (ViewGroup) findViewById(R.id.popup_element)); 
      // create a 300px width and 470px height PopupWindow 
      pw = new PopupWindow(layout, 300, 470, true); 
      // display the popup in the center 
      pw.showAtLocation(layout, Gravity.CENTER, 0, 0); 

      TextView WordPop = (TextView) layout.findViewById(R.id.textView2); 
      TextView PartsPop = (TextView) layout.findViewById(R.id.textView4); 
      TextView DescPop = (TextView) layout.findViewById(R.id.textView6); 
      TextView SentPop = (TextView) layout.findViewById(R.id.textView8); 
      WordPop.setText(list.getWord()); 
      PartsPop.setText(list.getParts()); 
      DescPop.setText(list.getDesc()); 
      SentPop.setText(list.getDesc()); 
      ImageButton cancelButton = (ImageButton) layout.findViewById(R.id.imageButton); 
      //makeBlack(cancelButton); 
      cancelButton.setOnClickListener(cancel_button_click_listener); 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

回答

0

在創建適配器實例時,您可以將片段中的活動上下文傳遞給適配器。

由於您已經在適配器中獲得了上下文。在其構造作爲一個參數到適配器

第一遍上下文 - 嘗試這個 - 片段的

LayoutInflater inflater = (LayoutInflater) this.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
//Inflate the view from a predefined XML layout 
    View layout = inflater.inflate(R.layout.popup_addword,(ViewGroup)this.activity.findViewById(R.id.popup_element)); 
+0

因爲我是新手,可以舉個例子。 –

+0

將代碼發佈到實例化適配器的位置。 –

+0

db = new WordBookHandler(getActivity()); wordList = db.getAllWords(); adapter = new WordBookAdapter(getActivity(),wordList); listView.setAdapter(adapter); –

0

getActivity()方法返回上下文,以便它可以被用來傳遞上下文這樣的適配器。 這可以通過使用getActivity()方法來完成的片段,以便初始化適配器的片段 -

YourAdapter adapter = new YourAdapter(getActivity(),YourOtherParameters...); 

然後在適配器構造函數應該像

//global 
Context context; 

public YourAdapter(Context context,YourOtherParameters...) { 
    this.context = context; 
} 

然後用此背景下膨脹圖。

LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
View layout = inflater.inflate(R.layout.popup_addword,(ViewGroup)context.findViewById(R.id.popup_element)); 
相關問題