带有可变文本的Android弹出窗口

时间:2016-04-16 08:09:59

标签: java android android-popupwindow

因此在弹出框中遇到一些麻烦,刚接触到android并且不确定如何解决这个问题。我想有一个基于公共变量显示特定文本的弹出窗口,因此当单击该按钮时,将检查该变量,并根据该变量的内容在textView中显示相应的文本。

  • 是否可以创建字符串变量,并使用一系列if语句将这些变量传递给textView?

  • 我是否需要为每个文件添加单独的布局文件,并使用if语句来确定将传递和弹出的视图?

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);  
   }});

非常感谢任何关于如何解决这个问题的帮助或指示

1 个答案:

答案 0 :(得分:1)

您可以使用此示例:

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);