Search code examples
javaandroidtextviewpopupwindowviewgroup

Change text of TextView in PopupWindow not working


I'm having problems dynamically changing the text in a TextView in a PopupWindow in Android. I've referenced the TextView element inside the PopupWindow by using a LayoutInflater and ViewGroup but the text is not updating. Any help would be very much appreciated! :)

My code is as follows:

private void popupWindow() {
        try {
            LayoutInflater inflater = (LayoutInflater) SwingSpeed.this
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View layout = inflater.inflate(R.layout.popup_recording,
                    (ViewGroup) findViewById(R.id.popup_element));
            pw = new PopupWindow(inflater.inflate(R.layout.popup_recording,
                    null, false), 480, 800, true);
            pw.showAtLocation(findViewById(R.id.swingspeed), Gravity.CENTER, 0,
                    0);
            recording_text = (TextView) layout
                    .findViewById(R.id.recording_text);
            recording_text.setText("Recording"); //Update the TextView  
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Solution

  • The problem is: you are inflating the layout two times, instead of:

    recording_text = (TextView) layout.findViewById(R.id.recording_text);
    

    do this:

    recording_text = (TextView) pw.getContentView().
                     findViewById(R.id.recording_text);
    

    and also, you don't need this line at all:

    View layout = inflater.inflate(R.layout.popup_recording,
                    (ViewGroup) findViewById(R.id.popup_element));