Android Button Highlight

本文介绍如何使用自定义图片在Android中实现按钮的不同状态显示,包括聚焦、按下和默认状态的图片设置。通过示例代码展示了如何创建XML文件来定义不同状态下的按钮背景。

In android, we can highlight the button through custom images. Here is a example that will give you about how to set a image when the button is focused, pressed and focused pressed. we can set each image for each stage.
Example for Android Button Highlight :-

01<?xml version="1.0" encoding="utf-8"?>
02<LinearLayout android:id="@+id/LinearLayout01"
03android:layout_width="fill_parent"
04android:layout_height="fill_parent"
06// Adding Button to Layout
07<Button android:id="@+id/Button01"
08android:background="@drawable/buttonhighlight"
09android:layout_height="60px"
10android:layout_width="100px"></Button>
11</LinearLayout>

Here “@drawable/buttonhighlight” is a XML file located in res/drawable folder. (see below image blue color highlighted)
buttonhighlight1
Create a XML file in res/drawable folder (ex:- buttonhighlight.xml) and write the code as

01<?xml version="1.0" encoding="utf-8"?>
02<selectorxmlns:android="http://schemas.android.com/apk/res/android">
03// Button Focused
04    <item android:state_focused="true"
05    android:state_pressed="false"
06    android:drawable="@drawable/buttonhighlightfocused" />
07// Button Focused Pressed
08    <item android:state_focused="true"
09    android:state_pressed="true"
10    android:drawable="@drawable/buttonhighlightpressed" />
11// Button Pressed
12    <item android:state_focused="false"
13    android:state_pressed="true"
14    android:drawable="@drawable/buttonhighlightpressed" />
15// Button Default Image
16    <item android:drawable="@drawable/buttonhighlightdefault"/>
17</selector>

The outputwill looks like
buttonhighlightdefault1buttonhighlightfocused1buttonhighlightpressed1

<?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
package com.example.test_001; import android.app.DatePickerDialog; import android.content.Intent; import android.database.Cursor; 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.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.example.test_001.db.AccountingDBHelper; import java.util.Calendar; public class SearchActivity extends AppCompatActivity { private ImageButton selectedCategoryButton = null; private TextView searchTitle; private EditText searchInput; private Button datePickerButton; private Button incomeButton; private Button expenseButton; private Button byAmountButton; private TextView resultTextView; private AccountingDBHelper dbHelper; private LinearLayout expenseCategoryGroup, expenseCategoryOther; private LinearLayout incomeCategoryGroup, incomeCategoryOther; // 收入类别按钮 private ImageButton salaryButton, debtButton, bonusButton, investmentButton, accidentButton, otherIncomeButton; // 支出类别按钮 private ImageButton foodButton, shoppingButton, utilitiesButton, phoneButton, entertainmentButton, otherOutcomeButton; private int selectedYear, selectedMonth, selectedDay; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search); // 初始化控件 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); byAmountButton = findViewById(R.id.by_amount_button); resultTextView = findViewById(R.id.result_text_view); expenseCategoryGroup = findViewById(R.id.expense_category_group_search_1); expenseCategoryOther = findViewById(R.id.expense_category_group_search_2); incomeCategoryGroup = findViewById(R.id.income_category_group_search_1); incomeCategoryOther = findViewById(R.id.income_category_group_search_2); // 收入图标按钮 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); // 支出图标按钮 foodButton = findViewById(R.id.category_food); shoppingButton = findViewById(R.id.category_shopping); utilitiesButton = findViewById(R.id.category_utilities); phoneButton = findViewById(R.id.category_phone); entertainmentButton = findViewById(R.id.category_entertainment); otherOutcomeButton = findViewById(R.id.category_other_outcome); // 找到返回按钮 Button backButton = findViewById(R.id.back_button); // 设置点击事件 backButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 创建 Intent 跳转到 MainActivity Intent intent = new Intent(SearchActivity.this, MainActivity.class); startActivity(intent); // 结束当前的 SearchActivity finish(); } }); // 初始化数据库帮助器 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); // 设置日期选择器按钮点击事件 datePickerButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showDatePickerDialog(); } }); setupCategoryButton(foodButton, "餐饮"); setupCategoryButton(shoppingButton, "购物"); setupCategoryButton(utilitiesButton, "水电费"); setupCategoryButton(phoneButton, "话费"); setupCategoryButton(entertainmentButton, "娱乐"); setupCategoryButton(otherOutcomeButton, "其他"); setupCategoryButton(salaryButton, "工资"); setupCategoryButton(debtButton, "收债"); setupCategoryButton(bonusButton, "奖金"); setupCategoryButton(investmentButton, "投资"); setupCategoryButton(accidentButton, "意外所得"); setupCategoryButton(otherIncomeButton, "其他收入"); // 默认显示支出类别 showExpenseCategories(); // 收入按钮点击 incomeButton.setOnClickListener(v -> { showIncomeCategories(); }); // 支出按钮点击 expenseButton.setOnClickListener(v -> { showExpenseCategories(); }); // 按金额搜索 byAmountButton.setOnClickListener(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); datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis()); 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()); } private void setupCategoryButton(ImageButton button, String categoryName) { button.setOnClickListener(v -> { if (selectedCategoryButton != null) { selectedCategoryButton.setBackgroundColor(getColor(android.R.color.transparent)); } selectedCategoryButton = button; selectedCategoryButton.setBackgroundColor(getColor(android.R.color.holo_blue_light)); 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[]{categoryName}, null, null, null); displayResults(cursor); }); } private void showIncomeCategories() { incomeButton.setBackgroundColor(getColor(android.R.color.holo_red_light)); expenseButton.setBackgroundColor(getColor(R.color.bg_gray)); // 隐藏支出类别 findViewById(R.id.expense_category_group_search_1).setVisibility(View.GONE); findViewById(R.id.expense_category_group_search_2).setVisibility(View.GONE); // 显示收入类别 findViewById(R.id.income_category_group_search_1).setVisibility(View.VISIBLE); findViewById(R.id.income_category_group_search_2).setVisibility(View.VISIBLE); } private void showExpenseCategories() { expenseButton.setBackgroundColor(getColor(android.R.color.holo_blue_light)); incomeButton.setBackgroundColor(getColor(R.color.bg_gray)); // 隐藏收入类别 findViewById(R.id.income_category_group_search_1).setVisibility(View.GONE); findViewById(R.id.income_category_group_search_2).setVisibility(View.GONE); // 显示支出类别 findViewById(R.id.expense_category_group_search_1).setVisibility(View.VISIBLE); findViewById(R.id.expense_category_group_search_2).setVisibility(View.VISIBLE); } } <?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"> <Button android:id="@+id/back_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="返回" android:layout_marginTop="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_marginTop="16dp"/> <!-- 搜索框与日历按钮 --> <LinearLayout android:id="@+id/search_input_container" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" 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="horizontal" android:layout_marginTop="20dp"> <Button android:id="@+id/income_button" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:text="收入" android:background="@color/bg_gray"/> <Button android:id="@+id/expense_button" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:text="支出" android:background="@color/bg_gray"/> </LinearLayout> <!-- 支出类别选择图标组 --> <!-- 支出类别图标组 --> <LinearLayout android:id="@+id/expense_category_group_search_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_search_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_search_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_search_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> <!-- 按金额查找按钮 --> <Button android:id="@+id/by_amount_button" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="按金额查找" android:layout_marginTop="20dp"/> <!-- 查询结果显示区域 --> <TextView android:id="@+id/result_text_view" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:textSize="16sp"/> </LinearLayout> </ScrollView> <?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.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; //以下是收入 case R.id.category_salary: category = "工资"; break; case R.id.category_collect_debt: category = "收债"; break; case R.id.category_bonus: category = "奖金"; break; case R.id.category_investment: category = "投资"; break; case R.id.category_accident: category = "意外所得"; break; case R.id.category_other_income: category = otherCategoryInput.getText().toString(); 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_income || id == R.id.category_other_outcome) && 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; } }综合分析以上代码,为什么在查找页面除了收入和支出的“其他类”之外的category都能够在只选定了对应category图标而未点击按金额查询的情况下显示出所有金额的对应数据,而收入和支出的“其他类”不可以?
06-28
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值