我试图从我的一个滑动视图(LayoutTwo类扩展Fragment)打开一个弹出窗口。我有下面的代码,但当我按下按钮时,没有任何反应..我认为传递我的观点有问题,但我不确定..有什么想法吗?
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
root = (ViewGroup) inflater.inflate(R.layout.layout_two, null);
this.container = container;
Button test = (Button) root.findViewById(R.id.bButton);
test.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
initiatePopupWindow();
}
});
return root;
}
private void initiatePopupWindow() {
try {
LayoutInflater inflater = (LayoutInflater) container.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.popup_layout,
(ViewGroup) container.findViewById(R.id.popup_element));
pw = new PopupWindow(layout, 300, 470, true);
pw.showAtLocation(layout, Gravity.CENTER, 0, 0);
TextView mResultText = (TextView) layout.findViewById(R.id.server_status_text);
Button cancelButton = (Button) layout.findViewById(R.id.end_data_send_button);
cancelButton.setOnClickListener(cancel_button_click_listener);
} catch (Exception e) {
e.printStackTrace();
}
}
修改
public class LayoutTwo extends Fragment {
private PopupWindow pw;
private ViewGroup root;
private Context C;
private ViewGroup container;
public static Fragment newInstance(Context context) {
LayoutTwo f = new LayoutTwo();
return f;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
root = (ViewGroup) inflater.inflate(R.layout.layout_two, null);
this.container = container;
Button test = (Button) root.findViewById(R.id.bButton);
test.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
initiatePopupWindow();
}
});
return root;
}
private void initiatePopupWindow() {
try {
LayoutInflater inflater = (LayoutInflater) container.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.popup_layout,
(ViewGroup) container.findViewById(R.id.popup_element));
View mainLayout = container.findViewById(R.id.linear);
pw = new PopupWindow(mainLayout, 300, 470, true);
pw.showAtLocation(mainLayout, Gravity.CENTER, 0, 0);
TextView mResultText = (TextView) layout.findViewById(R.id.server_status_text);
Button cancelButton = (Button) layout.findViewById(R.id.end_data_send_button);
cancelButton.setOnClickListener(cancel_button_click_listener);
} catch (Exception e) {
e.printStackTrace();
}
}
private OnClickListener cancel_button_click_listener = new OnClickListener() {
public void onClick(View v) {
pw.dismiss();
}
};
}
答案 0 :(得分:1)
当您致电PopupWindow.showAtLocation时,第一个参数应该是父视图,而不是自己的视图。
尝试这样做:
// assuming R.id.linear is the 'android:id' of your main view
View mainLayout = container.findViewById(R.id.linear);
pw.showAtLocation(mainLayout, Gravity.CENTER, 0, 0);
编辑:为了将来参考,请记住,您还可以通过执行以下两项操作之一来获取根视图:
包含状态栏
getWindow().getDecorView().findViewById(android.R.id.content)
不包括状态栏
((ViewGroup)findViewById(android.R.id.content)).getChildAt(0)