简体   繁体   中英

Calling method from within onClick(View v) switch (v.getId()

I am trying to change color of startButton within my :

onClick(View v) {
  switch (v.getId()) {
    case R.id.startButton:
    startButton.setTextColor(Color.RED);

    listenForNoise();
  break;}
}

private void listenForNoise(){
  /////******
return

but it only changes when my method listenForNoise returns. So there is a delay (method has a trigger-loop). How cam I make change color on pressing button?

you can call your "listenForNoise();" inside other thread ; some thing like this:

onClick(View v) {
switch (v.getId()) {
case R.id.startButton:
startButton.setTextColor(Color.RED);
new Thread(new Runnable() { 
        public void run(){        
listenForNoise();
        }
    }).start();
break;}
}
private void listenForNoise(){
/////******
return
}

onClick is invoked from the main/event/ui thread. It's fine that you update startButton's text color property from this thread however you want to avoid doing any work or io.

If the listentForNoise method has code that also modifies another view property and need to run in the same thread then you can post with a runnable.

startButton.post(new Runnable() {
    @Override
    public void run() {
        listenForNoise();
    }
})

Or create a new thread to invoke the method

new Thread(new Runnable() {
    @Override
    public void run() {
        listenForNoise();
    }
}).start();

or use an AsyncTask (look into Rx java for another approach)

 AsyncTask<Void, Void, Void> {

  protected Result doInBackground(String... someData) {
    // Any non blocking code for listenForNoise should go here
    return;
  }

  protected void onPostExecute(Void result) {
    // Any code that updates UI in listenForNoise should go here.
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM