我做了两个按钮,当点击开始按钮时,它在文本视图中显示当前时间。当点击停止按钮时,它也在文本视图中显示当前时间。 我的问题是,当我点击按钮上的多个时间时,它持续改变时间。我希望通过一次点击就能得到开始和停止的时间。我的意思是,我有一个按钮,当点击该按钮时,它在文本视图中显示当前的开始时间,并将该按钮的文本转为停止,然后当再次点击该按钮时,显示停止时间,并计算两个时间的差异并显示在文本视图中。
public class Aircraft extends Fragment {
TextView tvstarttime;
Button btn_start;
Button btn_end;
TextView tvend;
TextView diffence;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_aircraft, container, false);
tvstarttime = view.findViewById(R.id.txtstarttime);
btn_start = view.findViewById(R.id.btn_start);
btn_end= view.findViewById(R.id.btn_end);
tvend = view.findViewById(R.id.txtendtime);
diffence=view.findViewById(R.id.txtdifference);
btn_start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss aa");
String time1 = format.format(calendar.getTime());
tvstarttime.setText(time1);
btn_end.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss aa");
String time = format.format(calendar.getTime());
tvend.setText(time);
try {
Date date1 = format.parse(tvend.getText().toString());
Date date2 = format.parse(tvstarttime.getText().toString());
long mills = date1.getTime() - date2.getTime();
Log.v("Data1", ""+date1.getTime());
Log.v("Data2", ""+date2.getTime());
int hours = (int) (mills/(1000 * 60 * 60));
int mins = (int) (mills % (1000*60*60));
String diff = hours + ":" + mins;
diffence.setText(diff);
} catch (ParseException e) {
e.printStackTrace();
return view;