Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Showing a popup window from Fragment

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;
    }
}
like image 503
Salivan Avatar asked Mar 31 '14 21:03

Salivan


Video Answer


1 Answers

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

like image 68
Mina Fawzy Avatar answered Nov 03 '22 21:11

Mina Fawzy