PopupWindow在安卓PopupWindow

2023-09-12 03:02:00 作者:隔壁老王

要创建一个简单的工作PopupWindow,我们需要做到以下几点:

To create a simple working PopupWindow, we need to do the following:

popup_example.xml:

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

        <TextView         
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dip"
            android:text="Test Pop-Up" />

    </LinearLayout>

的Java code

LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

PopupWindow pw = new PopupWindow(inflater.inflate(R.layout.popup_example, null, false),100,100, true);

pw.showAtLocation(this.findViewById(R.id.main), Gravity.CENTER, 0, 0);

我的要求是,我需要一个

My requirement is that I need a

<TEXTVIEW android:layout_height="wrap_content" android:layout_width="fill_parent" />

<BUTTON android:id="@+id/end_data_send_button" android:text="Cancel"/>

在我的 popup_example.xml 。我怎么能在我的Java code处理这两种成分?

in my popup_example.xml. How can I handle these two components in my Java code?

推荐答案

在这里,我给你演示实例。根据您的需要看到这一点,对其进行自定义。

Here , I am giving you a demo example . See this and customize it according to your need.

public class ShowPopUp extends Activity {

     PopupWindow popUp;
     LinearLayout layout;
     TextView tv;
     LayoutParams params;
     LinearLayout mainLayout;
     Button but;
     boolean click = true;

     @Override
     public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      popUp = new PopupWindow(this);
      layout = new LinearLayout(this);
      mainLayout = new LinearLayout(this);
      tv = new TextView(this);
      but = new Button(this);
      but.setText("Click Me");
      but.setOnClickListener(new OnClickListener() {

       public void onClick(View v) {
        if (click) {
         popUp.showAtLocation(layout, Gravity.BOTTOM, 10, 10);
         popUp.update(50, 50, 300, 80);
         click = false;
        } else {
         popUp.dismiss();
         click = true;
        }
       }

      });
      params = new LayoutParams(LayoutParams.WRAP_CONTENT,
        LayoutParams.WRAP_CONTENT);
      layout.setOrientation(LinearLayout.VERTICAL);
      tv.setText("Hi this is a sample text for popup window");
      layout.addView(tv, params);
      popUp.setContentView(layout);
      // popUp.showAtLocation(layout, Gravity.BOTTOM, 10, 10);
      mainLayout.addView(but, params);
      setContentView(mainLayout);
     }
    }

希望这将解决您的问题。

Hope this will solve your issue.