-2

单击按钮时,我想打开一个对话框。在该对话框中,我想动态设置文本(有点像秒表),文本将通过循环出现。有人可以用示例代码指导我吗?我尝试了网上给出的许多示例,但未能成功实现结果。

//Button where the action starts
public void onClickStart(View v) {
    final Dialog dialog = new Dialog(MainActivity.this);
    dialog.setContentView(R.layout.activity_details);
    dialog.setTitle("Your Step Details");
    dialog.show();
    DisplayTask dd= new DisplayTask();
    dd.execute();
}

public void doWork(){
        final Handler handler=new Handler();
        new Thread(new Runnable (){
            boolean isRunning=true;
            @Override
            public void run() {
                while(isRunning){
                    try{
                        handler.post(new Runnable(){

                            @Override
                            public void run() {
                                try{
                                    TextView txtCurrentTime= (TextView)findViewById(R.id.txtLeft);
                                        Date dt = new Date();
                                        int hours = dt.getHours();
                                        int minutes = dt.getMinutes();
                                        int seconds = dt.getSeconds();
                                        String curTime = hours + ":" + minutes + ":" + seconds;
                                        txtCurrentTime.setText(curTime);
                                }catch (Exception e) {}

                            }

                        });
                    }catch(Exception e){

                    }
                }

            }

        }).start();
    }



public class DisplayTask extends AsyncTask<Void , Void, Void> {


    protected void onPostExecute(){
        MainActivity main= new Mai`enter code here`nActivity();
        main.doWork();
    }

    @Override
    protected Void doInBackground(Void... params) {
        onPostExecute();
        return null;
    }
}   
4

1 回答 1

0

If you want to do something on a timer, AsyncTask isn't the right method. Use a Handler, and post a message to it using postMessageDelayed. This will let you do something in a few milliseconds/seconds, but it will happen on the UI thread.

于 2013-04-06T20:23:04.923 回答