Android用DatePickerDialog如何让TextView显示日期并默认选中当天日期

本文介绍了如何在Android应用中使用DatePickerDialog实现TextView点击后显示日期选择,并默认选中当天日期。通过DatePickerDialog的OnDateSetListener监听器,可以在用户确认日期后立即触发数据请求。当月份小于10时,代码会自动在前面加上0。

前几天公司的一个需求是选择日期并默认选中当天日期。当时想的是默认选中当天日期那肯定是点击TextView再选择日历咯。于是乎,在网上搜了一下。下面放一下效果图在这里选择插入图片描述

选中日期的话我们可以用DatePickerDialog和DatePicker。下面我就用DatePickerDialog为例。

下面放代码~~~~

XML

 <LinearLayout
            android:id="@+id/down_choose_date"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/down_tv_choose_date"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="15dp"
                android:layout_marginTop="@dimen/dp_15"

                android:text="2019/12/28"
                android:textColor="@color/white" />

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="@dimen/dp_16"
                android:layout_marginLeft="5dp"
                android:background="@mipmap/dao_three" />

        </LinearLayout>

JAVA

//设置成员变量
private int mYear;
private int mMonth;
private int mDay;


//点击控件显示控件样式
new DatePickerDialog(getContext(),
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year,
                                          int month, int day) {
                        // TODO Auto-generated method stub
                        mYear = year;
                        mMonth = month;
                        mDay = day;
                        // 更新EditText控件日期 小于10加0
                        tvChooseDate.setText(new StringBuilder()
                                .append(mYear)
                                .append("/")
                                .append((mMonth + 1) < 10 ? "0"
                                        + (mMonth + 1) : (mMonth + 1))
                                .append("/")
                                .append((mDay < 10) ? "0" + mDay : mDay));
                    }
                }, calendar.get(Calendar.YEAR), calendar
                .get(Calendar.MONTH), calendar
                .get(Calendar.DAY_OF_MONTH)).show();
//设置默认选中当天日期


 //获取系统时间
     Calendar  calendar = Calendar.getInstance();
        //获取当前日期
        int year = calendar.get(Calendar.YEAR);

        int month = calendar.get(Calendar.MONTH) + 1;//特殊的是Calendar中月份从0开始计数,所以加1得到常规月份

        int day = calendar.get(Calendar.DAY_OF_MONTH);
        //将计算出来的年月日放到textview控件上
        tvChooseDate.setText(year + "/" + month + "/" + day);

那么问题又来了,选好日期之后如果想让它请求数据的话要怎么办呢?
我一开始在写这个的时候遇到了一个bug,就是我如果选择以前的日期让他显示当天的数据的话,只有点击两次这个控件他才能请求数据。后来查了DatePickerDialog 中有一个方法,就是OnDateSetListener(),选好日期之后,点击“确定”触发的事件。在这个方法里作数据的请求就可以了。
再贴一次第一次贴的代码

new DatePickerDialog(getContext(),
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year,
                                          int month, int day) {
                        // TODO Auto-generated method stub
                        mYear = year;
                        mMonth = month;
                        mDay = day;
                        // 更新EditText控件日期 小于10加0
                        tvChooseDate.setText(new StringBuilder()
                                .append(mYear)
                                .append("/")
                                .append((mMonth + 1) < 10 ? "0"
                                        + (mMonth + 1) : (mMonth + 1))
                                .append("/")
                                .append((mDay < 10) ? "0" + mDay : mDay));
                                //数据请求
                    }
                }, calendar.get(Calendar.YEAR), calendar
                .get(Calendar.MONTH), calendar
                .get(Calendar.DAY_OF_MONTH)).show();

如果我想要默认选中的当天日期(月份)小于10的时候前面加0,应该这么写

if (month < 10) { /*月份小于10  就在前面加个0*/
          String  defaultMonth = new String(new String(String.valueOf(0)) + new String(String.valueOf(month)));

        }
        if (day < 10) { /*日期小于10  就在前面加个0*/
           String  defaultDay = new String(new String(String.valueOf(0)) + new String(String.valueOf(day)));
        }
        L.d("defaultMonth---" + defaultMonth + "---defaultDay----" + defaultDay);
        tvChooseDate.setText(year + "/" + defaultMonth + "/" + defaultDay);

<?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <!-- 日期显示 --> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_marginBottom="16dp"> <TextView android:id="@+id/date_text" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:text="请选择日期" android:textSize="16sp"/> <Button android:id="@+id/date_picker_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="选择日期"/> </LinearLayout> <!-- 收支类型选择 --> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_marginBottom="16dp"> <Button android:id="@+id/income_button" android:layout_width="5dp" android:layout_height="wrap_content" android:layout_weight="1" android:background="@color/bg_gray" android:text="收入" /> <Button android:id="@+id/expense_button" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:background="@android:color/holo_blue_light" android:text="支出"/> </LinearLayout> <!-- 支出类别选择图标组 --> <LinearLayout android:id="@+id/expense_category_group_1" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_marginBottom="16dp"> <ImageButton android:id="@+id/category_food" android:layout_width="69dp" android:layout_height="wrap_content" app:srcCompat="@mipmap/hs_canyin_f" android:background="@color/button_default" /> <ImageButton android:id="@+id/category_shopping" android:layout_width="69dp" android:layout_height="wrap_content" android:background="@color/button_default" app:srcCompat="@mipmap/hs_gouwu_f" /> <ImageButton android:id="@+id/category_utilities" android:layout_width="69dp" android:layout_height="wrap_content" app:srcCompat="@mipmap/hs_shuidianfei_f" android:background="@color/button_default" /> <ImageButton android:id="@+id/category_phone" android:layout_width="69dp" android:layout_height="wrap_content" app:srcCompat="@mipmap/hs_tongxun_f" android:background="@color/button_default" /> <ImageButton android:id="@+id/category_entertainment" android:layout_width="69dp" android:layout_height="wrap_content" app:srcCompat="@mipmap/hs_yule_f" android:background="@color/button_default" /> </LinearLayout> <LinearLayout android:id="@+id/expense_category_group_2" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_marginBottom="16dp"> <ImageButton android:id="@+id/category_other_outcome" android:layout_width="69dp" android:layout_height="wrap_content" app:srcCompat="@mipmap/hs_qt_f" android:background="@color/button_default" /> </LinearLayout> <!-- 收入类别选择图标组 --> <LinearLayout android:id="@+id/income_category_group_1" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_marginBottom="16dp" android:visibility="gone"> <!-- 默认隐藏 --> <ImageButton android:id="@+id/category_salary" android:layout_width="69dp" android:layout_height="wrap_content" android:background="@color/button_default" app:srcCompat="@mipmap/hs_xinzi_f" /> <ImageButton android:id="@+id/category_collect_debt" android:layout_width="69dp" android:layout_height="wrap_content" android:background="@color/button_default" app:srcCompat="@mipmap/hs_shouzhai_f" /> <ImageButton android:id="@+id/category_bonus" android:layout_width="69dp" android:layout_height="wrap_content" android:background="@color/button_default" app:srcCompat="@mipmap/hs_jiangjin_f" /> <ImageButton android:id="@+id/category_investment" android:layout_width="69dp" android:layout_height="wrap_content" android:background="@color/button_default" app:srcCompat="@mipmap/hs_touzi_f" /> <ImageButton android:id="@+id/category_accident" android:layout_width="69dp" android:layout_height="wrap_content" android:background="@color/button_default" app:srcCompat="@mipmap/hs_yiwaisuode_f" /> </LinearLayout> <LinearLayout android:id="@+id/income_category_group_2" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_marginBottom="16dp" android:visibility="gone"> <ImageButton android:id="@+id/category_other_income" android:layout_width="69dp" android:layout_height="wrap_content" android:background="@color/button_default" app:srcCompat="@mipmap/hs_qita_f" /> </LinearLayout> <!-- 其他类别输入框(默认隐藏) --> <EditText android:id="@+id/other_category_input" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入类别" android:layout_marginBottom="16dp" android:visibility="gone" /> <!-- 金额输入 --> <EditText android:id="@+id/amount_input" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="金额" android:inputType="numberDecimal" android:layout_marginBottom="16dp"/> <!-- 提交按钮 --> <Button android:id="@+id/submit_button" android:layout_width="match_parent" android:layout_height="33dp" android:background="@color/colorPrimary" android:text="提交" android:textColor="@android:color/white" /> </LinearLayout> </ScrollView>package com.example.test_001; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import android.app.DatePickerDialog; import android.widget.TextView; import com.example.test_001.db.AccountingDBHelper; import com.example.test_001.enum_t.EnumType; import java.util.ArrayList; import java.util.Calendar; import java.util.List; public class RecordActivity extends AppCompatActivity { private ImageButton selectedImageButton = null; private TextView dateText; private Button datePickerButton; private LinearLayout expenseCategoryGroup, expenseCategoryOther; private LinearLayout incomeCategoryGroup, incomeCategoryOther; //支出按钮 private ImageButton foodButton; private ImageButton shoppingButton; private ImageButton utilitiesButton; private ImageButton phoneButton; private ImageButton otherOutcomeButton; private ImageButton entertainmentButton; //收入按钮 private ImageButton salaryButton, debtButton, bonusButton, investmentButton, accidentButton,otherIncomeButton; private EditText otherCategoryInput; private EditText amountInput; private Button submitButton; private AccountingDBHelper dbHelper; private Button incomeButton; private Button expenseButton; private EnumType selectedType = EnumType.EXPENSE; // 用于存储选中的收支类型 private int selectedYear, selectedMonth, selectedDay; private void setupImageButtonClickListener(ImageButton button) { button.setOnClickListener(v -> { if (selectedImageButton == button) { selectedImageButton.setBackgroundColor(getColor(R.color.button_default)); selectedImageButton = null; if (button.getId() == R.id.category_other_income || button.getId() == R.id.category_other_outcome) { otherCategoryInput.setVisibility(View.GONE); } } else { if (selectedImageButton != null) { selectedImageButton.setBackgroundColor(getColor(R.color.button_default)); } selectedImageButton = button; selectedImageButton.setBackgroundColor(getColor(R.color.yellow_highlight)); if (button.getId() == R.id.category_other_income || button.getId() == R.id.category_other_outcome) { otherCategoryInput.setVisibility(View.VISIBLE); } else { otherCategoryInput.setVisibility(View.GONE); } } }); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_record); //支出 foodButton = findViewById(R.id.category_food); shoppingButton = findViewById(R.id.category_shopping); utilitiesButton = findViewById(R.id.category_utilities); phoneButton = findViewById(R.id.category_phone); otherOutcomeButton = findViewById(R.id.category_other_outcome); entertainmentButton = findViewById(R.id.category_entertainment); //收入 salaryButton = findViewById(R.id.category_salary); debtButton = findViewById(R.id.category_collect_debt); bonusButton = findViewById(R.id.category_bonus); investmentButton = findViewById(R.id.category_investment); accidentButton = findViewById(R.id.category_accident); otherIncomeButton = findViewById(R.id.category_other_income); // 初始化控件 dateText = findViewById(R.id.date_text); datePickerButton = findViewById(R.id.date_picker_button); expenseCategoryGroup = findViewById(R.id.expense_category_group_1); expenseCategoryOther = findViewById(R.id.expense_category_group_2); incomeCategoryGroup = findViewById(R.id.income_category_group_1); incomeCategoryOther = findViewById(R.id.income_category_group_2); otherCategoryInput = findViewById(R.id.other_category_input); amountInput = findViewById(R.id.amount_input); submitButton = findViewById(R.id.submit_button); // 新增按钮初始化 incomeButton = findViewById(R.id.income_button); expenseButton = findViewById(R.id.expense_button); // 初始化数据库帮助器 dbHelper = new AccountingDBHelper(this); // 设置默认日期当前日期 final Calendar calendar = Calendar.getInstance(); selectedYear = calendar.get(Calendar.YEAR); selectedMonth = calendar.get(Calendar.MONTH); selectedDay = calendar.get(Calendar.DAY_OF_MONTH); updateDateDisplay(); // 设置日期选择器按钮点击事件 datePickerButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showDatePickerDialog(); } }); //因为默认是支出状态,而此时还没有进行对收入支出选项的点击,所以这里需要手动绑定支出图标的点击事件 setupImageButtonClickListener(foodButton); setupImageButtonClickListener(shoppingButton); setupImageButtonClickListener(utilitiesButton); setupImageButtonClickListener(phoneButton); setupImageButtonClickListener(entertainmentButton); setupImageButtonClickListener(otherOutcomeButton); //以下是分别把点击收入/支出这两个按钮的事件,和显示(收入/支出)、隐藏(支出/收入)图标组以及对应类别图标组的点击事件进行绑定(收入/支出) // 设置收入按钮点击事件 incomeButton.setOnClickListener(v -> { selectedType = EnumType.INCOME; incomeButton.setBackgroundColor(getColor(android.R.color.holo_red_light)); expenseButton.setBackgroundColor(getColor(R.color.bg_gray)); // 隐藏支出图标组 expenseCategoryGroup.setVisibility(View.GONE); expenseCategoryOther.setVisibility(View.GONE); // 显示收入图标组 incomeCategoryGroup.setVisibility(View.VISIBLE); incomeCategoryOther.setVisibility(View.VISIBLE); // 绑定收入图标点击事件 setupImageButtonClickListener(salaryButton); setupImageButtonClickListener(debtButton); setupImageButtonClickListener(bonusButton); setupImageButtonClickListener(investmentButton); setupImageButtonClickListener(accidentButton); setupImageButtonClickListener(otherIncomeButton); }); // 设置支出按钮点击事件 expenseButton.setOnClickListener(v -> { selectedType = EnumType.EXPENSE; expenseButton.setBackgroundColor(getColor(android.R.color.holo_blue_light)); incomeButton.setBackgroundColor(getColor(R.color.bg_gray)); // 隐藏收入图标组 incomeCategoryGroup.setVisibility(View.GONE); incomeCategoryOther.setVisibility(View.GONE); // 显示支出图标组 expenseCategoryGroup.setVisibility(View.VISIBLE); expenseCategoryOther.setVisibility(View.VISIBLE); // 恢复支出图标点击事件 setupImageButtonClickListener(foodButton); setupImageButtonClickListener(shoppingButton); setupImageButtonClickListener(utilitiesButton); setupImageButtonClickListener(phoneButton); setupImageButtonClickListener(entertainmentButton); setupImageButtonClickListener(otherOutcomeButton); }); // 设置提交按钮点击事件 submitButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 验证保存数据 if (validateInputs()) { String date = dateText.getText().toString(); String type=selectedType.getValue(); String category = null; if (selectedImageButton != null) { int id = selectedImageButton.getId(); switch (id) { case R.id.category_food: category = "餐饮"; break; case R.id.category_shopping: category = "购物"; break; case R.id.category_utilities: category = "水电"; break; case R.id.category_phone: category = "话费"; break; case R.id.category_other_outcome: category = otherCategoryInput.getText().toString(); break; case R.id.category_entertainment: category = "娱乐"; break; default: category = null; break; } } float amount = Float.parseFloat(amountInput.getText().toString()); // 使用addTransaction方法插入数据到数据库 dbHelper.addTransaction(date, type, category, amount); Toast.makeText(RecordActivity.this, "记录成功", Toast.LENGTH_SHORT).show(); finish(); // 返回到主页面 } } }); } private void showDatePickerDialog() { DatePickerDialog datePickerDialog = new DatePickerDialog(this, (view, year, monthOfYear, dayOfMonth) -> { selectedYear = year; selectedMonth = monthOfYear; selectedDay = dayOfMonth; updateDateDisplay(); }, selectedYear, selectedMonth, selectedDay); datePickerDialog.show(); } private void updateDateDisplay() { String formattedMonth = (selectedMonth + 1) < 10 ? "0" + (selectedMonth + 1) : String.valueOf(selectedMonth + 1); String formattedDay = selectedDay < 10 ? "0" + selectedDay : String.valueOf(selectedDay); dateText.setText(selectedYear + "-" + formattedMonth + "-" + formattedDay); } private boolean validateInputs() { // 验证日期是否选择 if (dateText.getText().toString().isEmpty()) { Toast.makeText(this, "请选择日期", Toast.LENGTH_SHORT).show(); return false; } // 验证类别是否选择(使用 ImageButton 判断) if (selectedImageButton == null) { Toast.makeText(this, "请选择类别", Toast.LENGTH_SHORT).show(); return false; } // 如果选择了"其他"但未输入自定义类别 int id = selectedImageButton.getId(); if (id == R.id.category_other && otherCategoryInput.getText().toString().isEmpty()) { Toast.makeText(this, "请输入自定义类别", Toast.LENGTH_SHORT).show(); return false; } // 验证金额为有效数字且大于0 try { double amount = Double.parseDouble(amountInput.getText().toString()); if (amount <= 0) { Toast.makeText(this, "金额必须大于0", Toast.LENGTH_SHORT).show(); return false; } } catch (NumberFormatException e) { Toast.makeText(this, "请输入有效的金额", Toast.LENGTH_SHORT).show(); return false; } return true; } }请仿照这两个程序修改以下两个程序实现收入与支出分别和对应的五个图标绑定(把单选按钮用图标按钮替换)package com.example.test_001; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.database.Cursor; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import android.widget.EditText; import android.widget.RadioGroup; import android.widget.RadioButton; import android.app.DatePickerDialog; import com.example.test_001.db.AccountingDBHelper; import java.util.Calendar; public class SearchActivity extends AppCompatActivity { private Button backButton; private TextView searchTitle; private EditText searchInput; private Button datePickerButton; private Button incomeButton; private Button expenseButton; private RadioGroup categoryGroup; private RadioButton categoryFood; private RadioButton categoryShopping; private RadioButton categoryUtilities; private RadioButton categoryPhone; private RadioButton categoryEntertainment; private RadioButton categoryOther; private Button byAmountButton; private TextView resultTextView; private AccountingDBHelper dbHelper; private int selectedYear, selectedMonth, selectedDay; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search); // 初始化控件 backButton = findViewById(R.id.back_button); // 返回按钮 searchTitle = findViewById(R.id.search_title); searchInput = findViewById(R.id.search_input); datePickerButton = findViewById(R.id.date_picker_button); incomeButton = findViewById(R.id.income_button); expenseButton = findViewById(R.id.expense_button); categoryGroup = findViewById(R.id.category_group); categoryFood = findViewById(R.id.category_food); categoryShopping = findViewById(R.id.category_shopping); categoryUtilities = findViewById(R.id.category_utilities); categoryPhone = findViewById(R.id.category_phone); categoryEntertainment = findViewById(R.id.category_entertainment); categoryOther = findViewById(R.id.category_other); byAmountButton = findViewById(R.id.by_amount_button); resultTextView = findViewById(R.id.result_text_view); // 初始化数据库帮助器 dbHelper = new AccountingDBHelper(this); // 设置返回按钮点击事件 backButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); // 返回到主页面 } }); // 获取当前日期作为默认选择日期 final Calendar calendar = Calendar.getInstance(); selectedYear = calendar.get(Calendar.YEAR); selectedMonth = calendar.get(Calendar.MONTH); selectedDay = calendar.get(Calendar.DAY_OF_MONTH); // 设置日期选择器按钮点击事件 datePickerButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showDatePickerDialog(); } }); // 设置收入按钮点击事件 incomeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Cursor cursor = dbHelper.getReadableDatabase().query( AccountingDBHelper.TABLE_TRANSACTIONS, new String[]{AccountingDBHelper.COLUMN_DATE, AccountingDBHelper.COLUMN_TYPE, AccountingDBHelper.COLUMN_CATEGORY, AccountingDBHelper.COLUMN_AMOUNT}, AccountingDBHelper.COLUMN_TYPE + "=?", // 查询条件 new String[]{"income"}, // 使用英文字段值进行查询 null, null, AccountingDBHelper.COLUMN_DATE + " ASC"); // 按日期升序排列 displayResults(cursor); } }); // 设置支出按钮点击事件 expenseButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Cursor cursor = dbHelper.getReadableDatabase().query( AccountingDBHelper.TABLE_TRANSACTIONS, new String[]{AccountingDBHelper.COLUMN_DATE, AccountingDBHelper.COLUMN_TYPE, AccountingDBHelper.COLUMN_CATEGORY, AccountingDBHelper.COLUMN_AMOUNT}, AccountingDBHelper.COLUMN_TYPE + "=?", // 查询条件 new String[]{"expense"}, // 使用英文字段值进行查询 null, null, AccountingDBHelper.COLUMN_DATE + " ASC"); // 按日期升序排列 displayResults(cursor); } }); // 设置类别单选组的监听器 categoryGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { String category = null; // 确定选择了哪个类别 switch (checkedId) { case R.id.category_food: category = "餐饮"; break; case R.id.category_shopping: category = "购物"; break; case R.id.category_utilities: category = "水电"; break; case R.id.category_phone: category = "话费"; break; case R.id.category_entertainment: category = "娱乐"; break; case R.id.category_other: category = "其他"; break; } if (category != null) { Cursor cursor = dbHelper.getReadableDatabase().query( AccountingDBHelper.TABLE_TRANSACTIONS, new String[]{AccountingDBHelper.COLUMN_DATE, AccountingDBHelper.COLUMN_TYPE, AccountingDBHelper.COLUMN_CATEGORY, AccountingDBHelper.COLUMN_AMOUNT}, AccountingDBHelper.COLUMN_CATEGORY + "=?", // 查询条件 new String[]{category}, // 查询条件参数 null, null, AccountingDBHelper.COLUMN_DATE + " ASC"); // 按日期升序排列 displayResults(cursor); } } }); // 设置按金额查找按钮点击事件 byAmountButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String amountStr = searchInput.getText().toString(); if (!amountStr.isEmpty()) { try { double amount = Double.parseDouble(amountStr); Cursor cursor = dbHelper.getReadableDatabase().query( AccountingDBHelper.TABLE_TRANSACTIONS, new String[]{AccountingDBHelper.COLUMN_DATE, AccountingDBHelper.COLUMN_TYPE, AccountingDBHelper.COLUMN_CATEGORY, AccountingDBHelper.COLUMN_AMOUNT}, AccountingDBHelper.COLUMN_AMOUNT + "=?", // 查询条件 new String[]{String.valueOf(amount)}, // 查询条件参数 null, null, null); displayResults(cursor); } catch (NumberFormatException e) { Toast.makeText(SearchActivity.this, "请输入有效的金额", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(SearchActivity.this, "请输入金额进行搜索", Toast.LENGTH_SHORT).show(); } } }); } private void showDatePickerDialog() { DatePickerDialog datePickerDialog = new DatePickerDialog(this, (view, year, monthOfYear, dayOfMonth) -> { selectedYear = year; selectedMonth = monthOfYear; selectedDay = dayOfMonth; updateDateDisplay(); }, selectedYear, selectedMonth, selectedDay); // 获取当前日期的时间戳 long currentMillis = System.currentTimeMillis(); datePickerDialog.getDatePicker().setMaxDate(currentMillis); // 限制最大日期为今天 datePickerDialog.show(); } private void updateDateDisplay() { String formattedMonth = (selectedMonth + 1) < 10 ? "0" + (selectedMonth + 1) : String.valueOf(selectedMonth + 1); String formattedDay = selectedDay < 10 ? "0" + selectedDay : String.valueOf(selectedDay); String date = selectedYear + "-" + formattedMonth + "-" + formattedDay; Cursor cursor = dbHelper.getReadableDatabase().query( AccountingDBHelper.TABLE_TRANSACTIONS, new String[]{AccountingDBHelper.COLUMN_DATE, AccountingDBHelper.COLUMN_TYPE, AccountingDBHelper.COLUMN_CATEGORY, AccountingDBHelper.COLUMN_AMOUNT}, AccountingDBHelper.COLUMN_DATE + "=?", // 查询条件 new String[]{date}, // 查询条件参数 null, null, null); displayResults(cursor); } private void displayResults(Cursor cursor) { if (cursor.getCount() == 0) { Toast.makeText(this, "没有找到匹配的数据", Toast.LENGTH_SHORT).show(); return; } StringBuilder result = new StringBuilder(); while (cursor.moveToNext()) { String date = cursor.getString(cursor.getColumnIndexOrThrow(AccountingDBHelper.COLUMN_DATE)); String type = cursor.getString(cursor.getColumnIndexOrThrow(AccountingDBHelper.COLUMN_TYPE)); String category = cursor.getString(cursor.getColumnIndexOrThrow(AccountingDBHelper.COLUMN_CATEGORY)); double amount = cursor.getDouble(cursor.getColumnIndexOrThrow(AccountingDBHelper.COLUMN_AMOUNT)); result.append("日期: ").append(date) .append(", 类型: ").append(type) .append(", 类别: ").append(category) .append(", 金额: ").append(amount) .append("\n"); } // 显示结果 resultTextView.setText(result.toString()); } }<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp" tools:context=".SearchActivity"> <!-- 返回按钮 --> <Button android:id="@+id/back_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="返回" android:layout_alignParentStart="true" android:layout_marginTop="16dp" android:layout_marginStart="16dp"/> <!-- 查找标题 --> <TextView android:id="@+id/search_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="查找页面" android:textSize="20sp" android:textStyle="bold" android:layout_centerHorizontal="true" android:layout_marginTop="16dp"/> <!-- 搜索框与日历按钮 --> <LinearLayout android:id="@+id/search_input_container" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_below="@id/search_title" android:layout_marginTop="16dp"> <EditText android:id="@+id/search_input" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:hint="输入搜索内容" android:inputType="text" android:layout_marginRight="8dp"/> <Button android:id="@+id/date_picker_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="📅" android:textSize="20sp"/> </LinearLayout> <!-- 查找按钮区域 --> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:layout_below="@id/search_input_container" android:layout_marginTop="20dp"> <!-- 收入/支出按钮 --> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_marginBottom="10dp"> <Button android:id="@+id/income_button" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:background="@color/bg_gray" android:text="收入"/> <Button android:id="@+id/expense_button" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:background="@color/bg_gray" android:text="支出"/> </LinearLayout> <!-- 类别单选组 --> <RadioGroup android:id="@+id/category_group" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_marginBottom="10dp"> <RadioButton android:id="@+id/category_food" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="餐饮"/> <RadioButton android:id="@+id/category_shopping" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="购物"/> <RadioButton android:id="@+id/category_utilities" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="水电"/> <RadioButton android:id="@+id/category_phone" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="话费"/> <RadioButton android:id="@+id/category_entertainment" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="娱乐"/> <RadioButton android:id="@+id/category_other" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="其他"/> </RadioGroup> <!-- 按金额查找按钮 --> <Button android:id="@+id/by_amount_button" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="按金额查找"/> <!-- 查询结果显示区域 --> <TextView android:id="@+id/result_text_view" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/by_amount_button" android:layout_marginTop="20dp" android:textSize="16sp"/> </LinearLayout> </RelativeLayout>
最新发布
06-28
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值