我想在用户点击列表项时显示一个弹出窗口。我在片段的Adapter Class中使用initiatePopWindow()
。如何解决findViewById
和ConfirmActivity
?
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 :(得分: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));
答案 1 :(得分:0)
首先在其构造函数中将上下文作为参数传递给适配器。 这可以通过使用片段的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));