I want to show a popup window from my PlaceHodler class extending Fragment when the button is clicked. For a test, I wrote this code which really works, but I guess it's ridiculous (using Button object as a parent view and so on... I couldn't find another way to make it work...). Please look at this code and advice me how to improve it. Please don't judge me because I'm a very beginner in programming.
My code:
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;
}
}
popwindow in fragment and activity almost the same except they way you get contrext , in activity this , fragment getActivity()
here is the code to create 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);
reference PopupWindow
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With