试图在线程中按下 PopupWindow 的按钮

Trying to press button of PopupWindow in thread

我有一个尝试连接到服务器的客户端。如果连接失败,5 秒后超时。我想打开一个没有连接符号和 "Try again to connect" 按钮的弹出窗口 window。弹出窗口是在线程中创建的,因此如果连接失败,线程将结束。正因如此,我把on click 方法放在了我的main activity 中。为什么它不起作用?

连接失败后线程运行的代码:

((Activity) context).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                LayoutInflater inflater = (LayoutInflater)
                        ((Activity) context).getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                final PopupWindow noConnection = new PopupWindow(
                        inflater.inflate(R.layout.popup_no_connection, null, false),
                        800,
                        800,
                        true);
                noConnection.setAnimationStyle(R.style.AnimationFade);
                noConnection.showAtLocation(((Activity) context).findViewById(R.id.entrance_layout), Gravity.CENTER, 0, 0);
                globalClass.getErrorHandler().setNoConnectionWithServer(noConnection);
            }
        });

主要代码 activity:

((GlobalClass) getApplicationContext()).initiateClass();
    globalClass = ((GlobalClass)getApplicationContext());

    LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View popupWindowView = inflater.inflate(R.layout.popup_no_connection, null, false);
    Button refreshConnection = (Button) popupWindowView.findViewById(R.id.btn_reconnect);
    refreshConnection.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (globalClass.getErrorHandler().getNoConnectionWithServer() != null) {
                Communication communication = new Communication(globalClass, entrance.this);
                globalClass.setCommunication(communication);
                Thread t = new Thread(communication);
                t.start();
                globalClass.getErrorHandler().getNoConnectionWithServer().dismiss();
            }
        }
    });

我猜你的动画不允许点击按钮。在没有动画的情况下试试这个。我有同样的问题,从左到右动画的按钮在动画期间和之后无法单击。它在没有动画的情况下工作。

当然不会调用onClick回调。为什么?因为:

// you find button in a view 
View popupWindowView = inflater.inflate(R.layout.popup_no_connection, null, false); // this return new view
Button refreshConnection = (Button) popupWindowView.findViewById(R.id.btn_reconnect);

// but you create pop up with another view not from above (which contain listener)
final PopupWindow noConnection = new PopupWindow(
                    inflater.inflate(R.layout.popup_no_connection, null, false),
                    800,
                    800,
                    true);

那么怎么解决呢?有两种方法:
1. 在 inflate 创建弹出视图后保存弹出视图,并在 runnable.
中创建弹出视图时重复使用 2. 在创建 pop-up view

后在 Runnable 中找到你的 ButtonsetOnclickListener