1

I have a popup window that contains 2 text views.

If user click on one text view toast must appear.I coded for this function but shows Nullpointer exception in line far.setOnClickListener(new OnClickListener() { Please help me on this.

My code :

btn_a.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            LayoutInflater lInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View popup_view = lInflater.inflate(R.layout.popup_a, null);
            final PopupWindow popup = new PopupWindow(popup_view,200,75,true);
            popup.setFocusable(true);
            popup.setBackgroundDrawable(new ColorDrawable());   
            popup.showAsDropDown(btn_a,  0,0);

            TextView far = (TextView) rootView.findViewById(R.id.fartext);
            far.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    Toast.makeText(getActivity(), "Clicked Far", Toast.LENGTH_SHORT).show();

                }
            });
        }
    });
Pavya
  • 6,015
  • 4
  • 29
  • 42
tenten
  • 1,276
  • 2
  • 26
  • 54

3 Answers3

5

Change this line

TextView far = (TextView) popup_view.findViewById(R.id.fartext);

instead of this

TextView far = (TextView) rootView.findViewById(R.id.fartext);
Abhishek Patel
  • 4,280
  • 1
  • 24
  • 38
3

You get a NullPointerException because you are trying to set a click listener on a view that is actually part of your popup_view and not rootView. Fix it like this:

TextView far = (TextView) popup_view.findViewById(R.id.fartext);
            far.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    Toast.makeText(getActivity(), "Clicked Far", Toast.LENGTH_SHORT).show();

                }
            });
Eric B.
  • 4,622
  • 2
  • 18
  • 33
3

The problem is your are looking in rootView where fareText is not exists. You should look into the inflated layout. Check below code.

btn_a.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        LayoutInflater lInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View popup_view = lInflater.inflate(R.layout.popup_a, null);
        final PopupWindow popup = new PopupWindow(popup_view,200,75,true);
        popup.setFocusable(true);
        popup.setBackgroundDrawable(new ColorDrawable());   
        popup.showAsDropDown(btn_a,  0,0);

        TextView far = (TextView) popup_view.findViewById(R.id.fartext);
        far.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Toast.makeText(getActivity(), "Clicked Far", Toast.LENGTH_SHORT).show();

            }
        });
    }
});
Ashish Tiwari
  • 2,168
  • 4
  • 30
  • 54