简体   繁体   English

从onClick(View v)开关(v.getId()

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

I am trying to change color of startButton within my : 我正在尝试在我的内部更改startButton的颜色:

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. 但是只有当我的方法listenForNoise返回时,它才会改变。 So there is a delay (method has a trigger-loop). 因此存在延迟(方法具有触发循环)。 How cam I make change color on pressing button? 我如何在按下按钮时改变颜色?

you can call your "listenForNoise();" 您可以调用“ 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. onClick是从main / event / ui线程调用的。 It's fine that you update startButton's text color property from this thread however you want to avoid doing any work or io. 您可以从该线程更新startButton的text color属性,但是可以避免进行任何工作或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. 如果listentForNoise方法的代码也修改了另一个view属性,并且需要在同一线程中运行,则可以使用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(查看Rx Java作为另一种方法)

 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.
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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