当从单独的类调用 PopupWindow 方法时,我希望能够从 xml 文件定义 PopupWindow 中的布局。下面的代码可以根据需要工作,除了布局是从 java 文件而不是 xml 文件中提取的。我不知道在这种情况下如何正确访问 xml 布局并在 PopupWindow 中实现,或者是否可能。感谢意见和具体建议。谢谢。
showPopup.java
public class showPopup {
Context ctx;
Button btnDismiss;
public showPopup(Context ctx){
this.ctx = ctx;
}
public void onCreateView(LayoutInflater layoutInflater, ViewGroup container) {
View layout = layoutInflater.inflate(R.layout.popup_layout, null);
btnDismiss = (Button) layout.findViewById(R.id.btndismissxml);
}
public void goJoe(View parent){
final PopupWindow popup = new PopupWindow(ctx);
btnDismiss = new Button (ctx);
btnDismiss.setText("Text is from showPopup.java");
popup.setContentView(btnDismiss);
popup.setWidth(400);
popup.setHeight(580);
popup.showAtLocation(parent, Gravity.CENTER_HORIZONTAL, 10, 10);
btnDismiss.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
popup.dismiss();
}
});
}
}
Tab3Fragment.java
public class Tab3Fragment extends Fragment implements OnClickListener{
Button btnPopup;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup containerGroup, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab3_fragment, containerGroup, false);
btnPopup = (Button)v.findViewById(R.id.btnPopupxml);
btnPopup.setOnClickListener(this);
return v;
}
//@Override
public void onViewCreated(View v) {
btnPopup = (Button)v.findViewById(R.id.btnPopupxml);
btnPopup.setOnClickListener(this);
}
@Override
public void onClick(View parent) {
new showPopup(getActivity().getApplicationContext()).goJoe(parent);
}
}
popup_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:id="@+id/layout">
<Button android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_width="wrap_content"
android:id="@+id/btndismissxml"
android:text="Text is from popup_layout.xml"></Button>
</RelativeLayout>
更新(1835 年,12 月 11 日):这是一个草稿弹出窗口。应用程序中将有几个服务用户可编辑的下拉字段。