最近工作需求需要用到PopupWindow ,MainActivity.java代码如下:
package com.example.administrator.popuwindow; import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.Gravity;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.PopupWindow;import android.widget.TextView; public class MainActivity extends AppCompatActivity{ private TextView textView; private PopupWindow popupWindow; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView)findViewById(R.id.tv); textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { popupWindow = new PopupWindow(LayoutInflater.from(MainActivity.this).inflate(R.layout.pop_list, null), ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true); popupWindow.showAtLocation(textView, Gravity.CENTER,0,0); } }); } }pop_list.xml 如下:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="160dp" android:layout_height="160dp" android:orientation="vertical" android:background="#ffffff" android:gravity="center" tools:context="com.example.administrator.popuwindow.MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="16dp" android:text="回复"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="16dp" android:text="删除"/></LinearLayout>
效果如图:
可是有个问题,只有按返回键才popuwindown才会消失,点击屏幕没有反应,在网上搜出的答案说是在
showAtLocation调用之前,加上以下两句,
popupWindow.setOutsideTouchable(true);popupWindow.setBackgroundDrawable(new BitmapDrawable());发现然并卵,百思不得其解,经过反复思考,发现这一段代码写得有问题:
popupWindow = new PopupWindow(LayoutInflater.from(MainActivity.this).inflate(R.layout.pop_list, null), ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);改成如下:
popupWindow = new PopupWindow(LayoutInflater.from(MainActivity.this).inflate(R.layout.pop_list, null), ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);原因很简单,因为前者这样写得话,popupWindow 把整个window都遮挡了,所以popupWindow.setOutsideTouchable(true)并没有起到作用,所以失效
时间: 2024-09-28 17:31:20