天文台秒表:当按下停止时,时间在后台不断增加

时间:2016-04-11 20:01:18

标签: android chronometer

当我按下停止按钮时,它会停止查看时间,但仍会在后台递增。当我按下开始时,它显示停止的整个时间。有谁知道如何让停止实际停止?

import android.app.Fragment;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Chronometer;

public class StopwatchFragment extends Fragment implements OnClickListener {


    public StopwatchFragment() {
        // Required empty public constructor
    }


    Button startChron;
    Button stopChron;
    Button resetChron;
    private Chronometer chron;



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_stopwatch_main, container, false);
        getActivity().getActionBar()
                .setTitle("Stopwatch");
        startChron = (Button)v.findViewById(R.id.start);
               startChron.setOnClickListener(this);
        stopChron = (Button)v.findViewById(R.id.stop);
               stopChron.setOnClickListener(this);
        resetChron = (Button)v.findViewById(R.id.reset);
               resetChron.setOnClickListener(this);
        chron = (Chronometer) v.findViewById(R.id.chronometer);
        return v;


    }

    @Override
    public void onClick(View v) {
        if (v == startChron){
            chron.start();
        }
        else if (v == stopChron){
            chron.stop();
        }
        else if (v == resetChron){
            chron.setBase(SystemClock.elapsedRealtime());
        }
    }
}

2 个答案:

答案 0 :(得分:0)

这是因为调用stop()不会改变您使用Chronometer设置的setBase()基数。如果您想重新开始Chronometer,那么每次拨打start()时,您都需要setBase()

chron.setBase(SystemClock.elapsedRealtime());

检查this

答案 1 :(得分:0)

您必须在变量中保存计时器暂停的时间。像这样:

difference = chron.getBase() - SystemClock.elapsedRealtime();

然后设置恢复时间:

time = timeDifference + SystemClock.elapsedRealtime()