1

私のアプリでは、押された特定のボタンを無効化/変更したいと考えています。

次のように簡略化された btnClicked という onclick メソッドがあります。

Public class MainActivity extends Activity{
     Button myBytton;

     @Override
     protected void onCreate(Bundle savedInstanceState) {
        myBytton = (Button)findViewById(R.id.buttonCall);
     } 
     public void btnClicked(View view)
     {
          myBytton.setText("loading");
          myBytton.setEnabled(false);
          myBytton.setClickable(false);
          // Do a call to an external api
          callApi();
     }

     public void callApi(){
          // run querys
          if(succesullyCalledApi){
                 vibrator.vibrate(500);
                 // I tried commenting out the below part, 
                 // it is than visible that the phone vibrates before it 
                 // has changed the text (atleast a quarter of a second).
                 myBytton.setText("search");
                 myBytton.setEnabled(true);
                 myBytton.setClickable(true);
          }
     }  
}

callApi メソッドには、関数が結果を取得した後に振動する vibrate メソッドがあります。また、callApi に結果があれば myButton が有効になり、テキストが検索に変更されます。

何が起こるかは次のとおりです。

ボタンをクリックすると、電話が最初に振動し、その後テキストが変わります。

私の質問。

myBytton.setText の前に callApi / vibrate が実行されたのはなぜですか?

4

3 に答える 3

0

UIスレッドですべてのことを行っているためです。長時間実行される操作にはAsyncTaskを使用する必要があります。

以下の実装を試してください:

public void callApi() {
  MyTask myTask = new MyTask();
  myTask.execute();
}


private class MyTask extends AsyncTask<Void, Void, Boolean> {
  protected void doInBackground(Void... params) {
    // This runs on a separate background thread

    boolean succesullyCalledApi = false;
    // run querys
    // do your long running query here and return its result.

    return succesullyCalledApi;
  }

  protected void onPostExecute(Boolean succesullyCalledApi) {
    // this runs on UI Thread

    if(succesullyCalledApi){
      vibrator.vibrate(500);
      myBytton.setText("search");
      myBytton.setEnabled(true);
      myBytton.setClickable(true);
    } else {
      // You should better think this part also. what will happen if result is false?
    }
  }

}
于 2015-05-04T22:50:53.673 に答える