帮我生成一个Android日期多选的代码
时间: 2024-01-21 14:18:48 浏览: 82
以下是一个简单的 Android 日期多选的示例代码,使用了 DatePickerDialog 和 Calendar 对象实现:
```java
public class MainActivity extends AppCompatActivity {
private TextView selectedDatesTextView;
private Button pickDatesButton;
private Calendar calendar;
private int year, month, day;
private HashSet<String> selectedDates;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
selectedDatesTextView = findViewById(R.id.selected_dates_text_view);
pickDatesButton = findViewById(R.id.pick_dates_button);
selectedDates = new HashSet<>();
pickDatesButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(MainActivity.this,
R.style.DatePickerTheme,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int selectedYear, int selectedMonth, int selectedDay) {
calendar.set(selectedYear, selectedMonth, selectedDay);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String selectedDate = sdf.format(calendar.getTime());
if (selectedDates.contains(selectedDate)) {
selectedDates.remove(selectedDate);
} else {
selectedDates.add(selectedDate);
}
updateSelectedDatesTextView();
}
}, year, month, day);
datePickerDialog.getDatePicker().setCalendarViewShown(false);
datePickerDialog.setCancelable(false);
datePickerDialog.show();
}
});
}
private void updateSelectedDatesTextView() {
if (selectedDates.isEmpty()) {
selectedDatesTextView.setText("No dates selected.");
} else {
StringBuilder stringBuilder = new StringBuilder();
for (String date : selectedDates) {
stringBuilder.append(date).append("\n");
}
selectedDatesTextView.setText(stringBuilder.toString());
}
}
}
```
在布局文件中,可以添加一个 TextView 和一个 Button:
```xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/pick_dates_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pick Dates"
android:layout_centerInParent="true"/>
<TextView
android:id="@+id/selected_dates_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:textStyle="bold"
android:layout_below="@+id/pick_dates_button"
android:layout_marginTop="16dp"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
```
这份代码会在用户点击按钮时弹出一个日期选择器,用户可以选择多个日期,选择的日期会显示在 TextView 中。你可以根据需要进行修改和优化。
阅读全文