为了账号安全,请及时绑定邮箱和手机立即绑定

如何在Android中创建弹出窗口(PopupWindow)

如何在Android中创建弹出窗口(PopupWindow)

慕仙森 2019-11-13 14:57:52
要创建一个简单的工作PopupWindow,我们需要执行以下操作: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代码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);我的要求是我需要一个<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代码中处理这两个组件?
查看完整描述

3 回答

?
catspeake

TA贡献1111条经验 获得超0个赞

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


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

     }

    }

希望这能解决您的问题。


查看完整回答
反对 回复 2019-11-13
  • 3 回答
  • 0 关注
  • 884 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信