如何在 Android Studio 中构建年龄计算器?
你好极客,今天我们将制作一个应用程序来计算两个日期之间的年龄或时间段。通过制作此应用程序,您可以计算出他/她的确切年龄,也可以计算出两个日期之间的确切差异。
先决条件:
在制作此应用程序之前,您可以先阅读程序计算年龄一文,以便更好地了解此应用程序中使用的概念。
我们将在本文中构建什么?
在此应用程序中,我们将使用两个 DatePicker,用户可以在其中选择日期编号。分别为 1 和 2。一个 Button 用于执行计算部分,并将结果显示在一个名为 result 的 TextView 中。请注意,我们将使用Java语言实现此应用程序。下面给出了一个示例视频,以了解我们将在本文中做什么。
分步实施
第 1 步:创建一个新项目
- 打开一个新项目。
- 我们将使用Java语言处理 Empty Activity。保持所有其他选项不变。
- 您可以在方便时更改项目的名称。
- 将有两个名为activity_main.xml 和 MainActivity 的默认文件。Java。
如果您不知道如何在 Android Studio 中创建新项目,那么您可以参考如何在 Android Studio 中创建/启动新项目?
第 2 步:导航到 Build scripts > build.gradle(module) 文件并向其添加以下依赖项
implementation 'joda-time:joda-time:2.9.1'
步骤 3:使用 activity_main.xml 文件
在这里,我们将设计应用程序的用户界面。我们将在各自的作品中使用以下组件:
- 按钮 1:选择用户想要输入的第一个日期。
- 按钮 2:选择用户想要输入的第二个日期。
- 按钮 3:执行计算
- TextView:显示最终输出(年龄)。
导航到app > res > layout > activity_main.xml并将以下代码添加到该文件中。
XML
Java
import android.app.DatePickerDialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import org.joda.time.Period;
import org.joda.time.PeriodType;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
// initializing variables
Button btn_birth, btn_today, btn_calculate;
TextView tvResult;
DatePickerDialog.OnDateSetListener dateSetListener1, dateSetListener2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// assign variables
btn_birth = findViewById(R.id.bt_birth);
btn_today = findViewById(R.id.bt_today);
btn_calculate = findViewById(R.id.btn_calculate);
tvResult = findViewById(R.id.tv_result);
// calendar format is imported to pick date
Calendar calendar = Calendar.getInstance();
// for year
int year = calendar.get(Calendar.YEAR);
// for month
int month = calendar.get(Calendar.MONTH);
// for date
int day = calendar.get(Calendar.DAY_OF_MONTH);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
// to set the current date as by default
String date = simpleDateFormat.format(Calendar.getInstance().getTime());
btn_today.setText(date);
// action to be performed when button 1 is clicked
btn_birth.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// date picker dialog is used
// and its style and color are also passed
DatePickerDialog datePickerDialog = new DatePickerDialog(MainActivity.this, android.R.style.Theme_Holo_Light_Dialog_MinWidth, dateSetListener1, year, month, day
);
// to set background for datepicker
datePickerDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
datePickerDialog.show();
}
});
// it is used to set teh date which user selects
dateSetListener1 = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int day) {
// here month+1 is used so that
// actual month number can be displayed
// otherwise it starts from 0 and it shows
// 1 number less for every month
// example- for january month=0
month = month + 1;
String date = day + "/" + month + "/" + year;
btn_birth.setText(date);
}
};
// action to be performed when button 2 is clicked
btn_today.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// date picker dialog is used
// and its style and color are also passed
DatePickerDialog datePickerDialog = new DatePickerDialog(MainActivity.this, android.R.style.Theme_Holo_Light_Dialog_MinWidth, dateSetListener2, year, month, day
);
// to set background for datepicker
datePickerDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
datePickerDialog.show();
}
});
// it is used to set teh date which user selects
dateSetListener2 = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int day) {
// here month+1 is used so that
// actual month number can be displayed
// otherwise it starts from 0 and it shows
// 1 number less for every month
// example- for january month=0
month = month + 1;
String date = day + "/" + month + "/" + year;
btn_today.setText(date);
}
};
// action to be performed when calculate button is clicked
btn_calculate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// converting the inputted date to string
String sDate = btn_birth.getText().toString();
String eDate = btn_today.getText().toString();
SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("dd/MM/yyyy");
try {
// converting it to date format
Date date1 = simpleDateFormat1.parse(sDate);
Date date2 = simpleDateFormat1.parse(eDate);
long startdate = date1.getTime();
long endDate = date2.getTime();
// condition
if (startdate <= endDate) {
org.joda.time.Period period = new Period(startdate, endDate, PeriodType.yearMonthDay());
int years = period.getYears();
int months = period.getMonths();
int days = period.getDays();
// show the final output
tvResult.setText(years + " Years |" + months + "Months |" + days + "Days");
} else {
// show message
Toast.makeText(MainActivity.this, "BirthDate should not be larger then today's date!", Toast.LENGTH_SHORT).show();
}
} catch (ParseException e) {
e.printStackTrace();
}
}
});
}
}
执行上述代码后, activity_main.xml文件的设计是这样的。
第 4 步:使用 MainActivity。 Java文件
在主活动中。 Java文件 onClickListerner 用于按钮选择日期和执行计算。在MainActivity 中使用以下代码。 Java文件。
Java
import android.app.DatePickerDialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import org.joda.time.Period;
import org.joda.time.PeriodType;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
// initializing variables
Button btn_birth, btn_today, btn_calculate;
TextView tvResult;
DatePickerDialog.OnDateSetListener dateSetListener1, dateSetListener2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// assign variables
btn_birth = findViewById(R.id.bt_birth);
btn_today = findViewById(R.id.bt_today);
btn_calculate = findViewById(R.id.btn_calculate);
tvResult = findViewById(R.id.tv_result);
// calendar format is imported to pick date
Calendar calendar = Calendar.getInstance();
// for year
int year = calendar.get(Calendar.YEAR);
// for month
int month = calendar.get(Calendar.MONTH);
// for date
int day = calendar.get(Calendar.DAY_OF_MONTH);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
// to set the current date as by default
String date = simpleDateFormat.format(Calendar.getInstance().getTime());
btn_today.setText(date);
// action to be performed when button 1 is clicked
btn_birth.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// date picker dialog is used
// and its style and color are also passed
DatePickerDialog datePickerDialog = new DatePickerDialog(MainActivity.this, android.R.style.Theme_Holo_Light_Dialog_MinWidth, dateSetListener1, year, month, day
);
// to set background for datepicker
datePickerDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
datePickerDialog.show();
}
});
// it is used to set teh date which user selects
dateSetListener1 = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int day) {
// here month+1 is used so that
// actual month number can be displayed
// otherwise it starts from 0 and it shows
// 1 number less for every month
// example- for january month=0
month = month + 1;
String date = day + "/" + month + "/" + year;
btn_birth.setText(date);
}
};
// action to be performed when button 2 is clicked
btn_today.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// date picker dialog is used
// and its style and color are also passed
DatePickerDialog datePickerDialog = new DatePickerDialog(MainActivity.this, android.R.style.Theme_Holo_Light_Dialog_MinWidth, dateSetListener2, year, month, day
);
// to set background for datepicker
datePickerDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
datePickerDialog.show();
}
});
// it is used to set teh date which user selects
dateSetListener2 = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int day) {
// here month+1 is used so that
// actual month number can be displayed
// otherwise it starts from 0 and it shows
// 1 number less for every month
// example- for january month=0
month = month + 1;
String date = day + "/" + month + "/" + year;
btn_today.setText(date);
}
};
// action to be performed when calculate button is clicked
btn_calculate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// converting the inputted date to string
String sDate = btn_birth.getText().toString();
String eDate = btn_today.getText().toString();
SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("dd/MM/yyyy");
try {
// converting it to date format
Date date1 = simpleDateFormat1.parse(sDate);
Date date2 = simpleDateFormat1.parse(eDate);
long startdate = date1.getTime();
long endDate = date2.getTime();
// condition
if (startdate <= endDate) {
org.joda.time.Period period = new Period(startdate, endDate, PeriodType.yearMonthDay());
int years = period.getYears();
int months = period.getMonths();
int days = period.getDays();
// show the final output
tvResult.setText(years + " Years |" + months + "Months |" + days + "Days");
} else {
// show message
Toast.makeText(MainActivity.this, "BirthDate should not be larger then today's date!", Toast.LENGTH_SHORT).show();
}
} catch (ParseException e) {
e.printStackTrace();
}
}
});
}
}
恭喜!我们已经成功地应用了计算两个日期之间的年龄或差异的应用程序。这是我们应用程序的最终输出。
输出: