2013-06-05 24 views
0

按下按钮时,应用程序会尝试将数据发送到服务器。如果连接处于活动状态,则会立即发送数据,但如果链路断开,系统会尝试发送x秒。事实上,在这段时间内,界面被(有意)阻塞(按钮点亮以突出显示当前操作)。问题是,如果用户开始按下其他按钮,则会听到事件,并在连接变为活动状态时执行与这些事件相关的所有操作。
我该如何预防?
如何防止如何防止与其他按钮相关的每个事件被处理? 任何建议将不胜感激。Android:单击按钮后丢弃的事件

编辑 我已经尝试过检查按下按钮时,不幸的是,当该标志重新设置好的,所有事件都被获取,并执行一个标志:

public void onClick(View v) {     
    switch(v.getId()) 
    { 

    case R.id.button1: //when sendData() is trying to send the message, I don't want to that this code is executed 
     if(flagConf == 1) 
     { 
       ...do something... 
     } 
     break; 
    case R.id.buttonConfirm: 

     if(myFlag == 1) //to avoid multiple touch of this button 
     { 
      ...do something... 
      myFlag = 0; 
      sendData(); 
      if(dataSent)  
      ...do something... 
      else 
      ...do something... 
      myFlag = 1; //I set this flag to 1 because, if message is not sent, the user have to re-pressed the buttonConfirm and try again 
     }  
    break; 
    } 
} 

以及其他按钮听众:

感谢

回答

1

你可以简单地使用,同时将数据处理设定为像boolean = true;的标志。然后检查每个ButtononClick

public void onClick(View v) 
{ 
    if (!sending) 
    { 
     // do stuff 
    } 
} 

如果sendingtrue那么Button不会做任何事情。请记住在处理完您的数据或其他内容后,将flag设置回false。你也可以使用buttonName.setEnabled(false);在你完成之后,你可以使用'then back to'。

边注:如果此操作需要很长的都(比一两秒钟或许更多),我会劝阻反对而不是让他们做任何事情,因为人们已经变得很不耐烦的生物。没有人愿意坐下来看几秒钟的旋转圈。然而,如果您选择这样做,那么您可能想要显示一些消息,以便他们知道为什么Buttons不起作用

+0

不幸的是,我已经这样做了,但所有其他事件都被捕获了......当连接打开时,所有事件都被处理。 – Ant4res

+0

嗯......除非你的代码中还有别的东西出现,否则这是毫无意义的。你已经在'onClick'中试过了上面的代码,代码仍然运行?如果是这种情况,那么你可能想要发布一些代码,所以我们可以看到究竟发生了什么 – codeMagic

+0

我编辑了我的问题,谢谢。 – Ant4res

1

我有类似的问题。而且有一个很好的和干净的方式来解决这个问题。

我与服务器的连接是通过扩展AsyncTask的类完成的。这样,每次我按下按钮,我都会检查任务是否正在运行。如果不是,它会产生一个新的任务并执行该任务。

public void onClick(View v) { 
    if (updateThread == null){ 

     updateThread = new UpdateThreadClass(); 
     updateThread.execute(); 
    } 
} 

然后创建的AsyncTask,如:

public class UpdateThreadsClass extends AsyncTask<String, Void, Boolean> { 
    @Override 
    protected Boolean doInBackground(String... params) { 

     // Your code 
    } 

    @Override 
    protected void onPostExecute(final Boolean success) { 

     // Execute after completing the connection 
    } 
} 

声明变量updateThread全球那么你的好去。

如果你愿意,你可以通过之前的任务已经完成,也可以可以为按键做同样的改变后的可见性(在onClick.setVisibility(View.VISIBLE).setVisibility(View.Gone))或者激活您的XML一个进度条。

编辑

你可以把进度条在XML像这样:

<ProgressBar 
      android:id="@+id/loading_screen" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_centerHorizontal="true" 
      android:layout_centerVertical="true" 
      android:gravity="center_vertical|center_horizontal" 
      android:visibility="gone"/> 

然后点击按钮后,只是不喜欢loadingScreen = (ProgressBar) findViewById(R.id.loading_screen),并设置能见度可见。

+0

感谢您的回答。不幸的是我不能使用AsyncTask。如果我不使用它,我可以添加进度条吗? – Ant4res

+0

是的,你可以!让我编辑答案,然后添加片段。 – Akatosh

+0

谢谢,这对我非常有用! – Ant4res