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

时间:2016-03-22 10:19:48

标签: java android multithreading onclicklistener popupwindow

我有一个尝试连接服务器的客户端。如果连接失败,则在5秒后出现超时。我想知道打开一个没有连接标志的弹出窗口"再试一次连接"按钮。弹出窗口是在线程中创建的,因此如果连接失败,则线程结束。因此,我将点击方法放在我的主要活动中。为什么不起作用?

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

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

主要活动中的代码:

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

当然,不会调用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.创建Button

后,在setOnclickListener内找到您的Runnablepop-up view