Search code examples
javaandroidandroid-popupwindow

Android Popup Window with Variable Text


So having a bit of trouble with a popup box, new to android and not sure how to go about this. I would like to have a popup that displays specific text based on a public variable, so when the button is clicked, the variable is checked, and depending on what that variable is the appropriate text is displayed in the textView.

  • Is is possible to create string variables, and with a series of if statements pass those variables to the textView?

  • Do I need individual layout files for each one and use the if statements to determine what view will be be passed and popped up?

popup.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

        <TextView
            android:id="@+id/text_id"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="" />

    <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Close"
            android:id="@+id/button1"/>     

</LinearLayout>

mainActivity.java

 Button pubtn = (Button)findViewById(R.id.popupOpen);
 pubtn.setOnClickListener(new Button.OnClickListener(){

   @Override
   public void onClick(View arg0) {
    LayoutInflater layoutInflater = (LayoutInflater)getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);  

    View puView = layoutInflater.inflate(R.layout.popup, null);  
    PopupWindow puWindow = new PopupWindow(
               puView, 
               LayoutParams.WRAP_CONTENT,  
               LayoutParams.WRAP_CONTENT);  

             Button btnExit = (Button)puView.findViewById(R.id.button1);
             btnExit.setOnClickListener(new Button.OnClickListener(){

     @Override
     public void onClick(View v) {
      puWindow.dismiss();
     }});
             puWindow.showAsDropDown(pubtn, 0, 0);  
   }});

any help or direction on how to go about this would be much appreciated


Solution

  • You can use this example:

    LayoutInflater inflater = (LayoutInflater) YourActivity.this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.popup_xml,
                (ViewGroup) findViewById(R.id.popup_element));
        popupWindow = new PopupWindow(layout, 300, 190, true);
    
        popupText = (TextView) layout.findViewById(R.id.popupText);
        popupText.setText(yourString);