2013-08-05 68 views
0

我有一个非常简单的测试应用程序,并设置seekBar的位置我正在使用可运行。尽管我实际上使用可运行的程序的经验很少。Java可运行似乎没有在Android中触发

public class MySpotify extends Activity implements Runnable { 

    private SeekBar progress; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.spotify_app); 
     myProgress = (SeekBar) findViewById(R.id.myBar); 
    } 

    @Override 
    public void run() { 
     myProgress.setProgress(25); 
    } 
} 

如果我将myProgress.setProgress(25);移动到onCreate,那么它的工作原理。但我希望它能在可运行的环境中出现。有任何想法吗?

+1

东西必须运行'Runnable'。这可以是一个单独的线程,方法'Activity.runOnUiThread()'或直接调用'run()' –

+0

正如@MichaelButscher所说,它需要由某人启动。 (new MySpotify()),start(),runOnUIThread(new MySpotify())或myProgress.post(new MySpotify())。您应该阅读关于线程并重新考虑您的设计,让整个Runnable类更新进度是没有意义的。你甚至可以有一个正常的活动类和类似myProgress.post(新的Runnable(){公共无效运行(myProgress.setProgress(25))});或new Thread(new Runnable(){public void run(myProgress.setProgress(25))})。start(); – momo

回答

0

您需要将post() a Runnable设置为Thread才能执行。尝试在onCreate()内拨打post(this);

+0

只是试了一下。 '方法post()是未定义的。“# – EGHDK

+0

你可以做一个'runOnUiThread(this)'。在视图上发布 – sriramramani

+0

。 myProgress.post(this) – momo

0

尝试

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.spotify_app); 
    myProgress = (SeekBar) findViewById(R.id.myBar); 

    myProgress.post(new Runnable() 
    {  
     public void run() 
     { 
      myProgress.setProgress(25); 
     } 
    }); 
} 

你需要的东西就

+0

我的应用程序似乎现在抛出一个没有响应的窗口。有任何想法吗? – EGHDK

+0

您是否设置了任何断点以查看它是否通过了该点或者它是否卡在那里?我不相信代码应该给你。虽然,我并不经常使用'Runnable'。如果我需要这样的话,我通常使用'AsyncTask'。 – codeMagic

+0

我没有设置任何断点,但是如果我让它运行30秒,然后我得到没有响应的对话框。 – EGHDK

0

运行post()方法您可以通过只调用运行开始运行方法(); 请注意,它将在主线程上执行。 也请注意,它只会运行一次,因为没有循环。

如果你想更新,而做其他事情你应该创建一个新的线程。

例如:

public class MySpotify extends Activity{ 

    private SeekBar myProgress; //I asume it is call "myProgress" instead of "progress" 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.spotify_app); 
     myProgress = (SeekBar) findViewById(R.id.myBar); 

     ThreadExample example = new ThreadExample(); 
     example.start(); 
     /* Start a new thread that executes the code in the thread by creating a new thread. 
     * If ou call example.run() it will execute on the mainthread so don't do that. 
     */ 
    } 

    private class ThreadExample extends Thread{ 
     public void run() { 
      myProgress.setProgress(25); 
     }      
    } 
} 
相关问题