在下一个动作之前安卓延迟

时间:2014-04-18 15:58:12

标签: android sdk delay android-progressbar

在我的新Android应用中,我需要按一个按钮来使visibile成为一个进度条,但我需要在3秒后让它隐身。

我在网上发现了这个但它不起作用:

public void search(View view) throws InterruptedException {
ProgressBar progressbarSearch = (ProgressBar) findViewById(R.id.progressBar);
    Button searchbutton = (Button) findViewById(R.id.button);
progressbarSearch.setVisibility(1);
    searchbutton.setText("Searching devices...");

    Handler myHandler = new Handler();
    //this waits 3 seconds, then will call the run() method below.
    myHandler.postDelayed(stopSearching, 3000);


}

private Runnable stopSearching = new Runnable()
{
    @Override
    public void run()
    {
        ProgressBar progressbarSearch = (ProgressBar) findViewById(R.id.progressBar);
        progressbarSearch.setVisibility(0);
    }
};

错误在哪里?按下按钮后进度条开始,但3秒后不会变为不可见。

2 个答案:

答案 0 :(得分:0)

progressbarSearch.setVisibility( View.INVISBLE );

你应该在这里使用常量,它确实容易出错并且无法维护使用值。 (通过例子证明:))

答案 1 :(得分:0)

Button searchbutton = (Button) findViewById(R.id.button);
    searchbutton.setText("Searching devices...");
    searchbutton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            ProgressBar progressbarSearch = (ProgressBar) findViewById(R.id.progressBar1);
            progressbarSearch.setVisibility(View.VISIBLE);
            try {
                search(v);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });

}

public void search(View view) throws InterruptedException {

    Handler myHandler = new Handler();
    // this waits 3 seconds, then will call the run() method below.
    myHandler.postDelayed(stopSearching, 3000);

}

private Runnable stopSearching = new Runnable() {
    @Override
    public void run() {
        ProgressBar progressbarSearch = (ProgressBar) findViewById(R.id.progressBar1);
        progressbarSearch.setVisibility(View.INVISIBLE);

    }
};

像这样更改您的代码