使用android studio创建一个Fragment来允许用户输入每天的收入和支出。在布局文件中添加适当的UI元素和逻辑代码,并使用Room数据库来存储用户输入。
时间: 2023-06-18 22:04:50 浏览: 139
好的,下面是实现步骤:
1. 创建一个新的Android Studio项目,并添加以下依赖项到build.gradle文件中:
```groovy
dependencies {
def room_version = "2.3.0"
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
implementation "androidx.room:room-ktx:$room_version"
}
```
2. 创建一个名为Expense的数据类,用于表示用户的每日收入和支出信息,并添加@Entity注释以指示该类应该存储在Room数据库中。在该类中添加必要的属性和方法:
```kotlin
@Entity(tableName = "expenses")
data class Expense(
@PrimaryKey(autoGenerate = true)
val id: Int = 0,
val date: Date,
val income: Double,
val expenditure: Double
)
```
3. 创建一个名为ExpenseDao的接口,用于定义访问Expense对象的数据库操作。在接口中添加必要的方法,如插入、查询和更新:
```kotlin
@Dao
interface ExpenseDao {
@Query("SELECT * FROM expenses")
fun getAllExpenses(): List<Expense>
@Query("SELECT * FROM expenses WHERE date = :date")
fun getExpenseByDate(date: Date): Expense?
@Insert
fun addExpense(expense: Expense)
@Update
fun updateExpense(expense: Expense)
@Delete
fun deleteExpense(expense: Expense)
}
```
4. 创建一个名为ExpenseDatabase的抽象类,用于定义ExpenseDao的实例。在该类中添加必要的注释和方法:
```kotlin
@Database(entities = [Expense::class], version = 1)
abstract class ExpenseDatabase : RoomDatabase() {
abstract fun expenseDao(): ExpenseDao
companion object {
private var INSTANCE: ExpenseDatabase? = null
fun getDatabase(context: Context): ExpenseDatabase {
val tempInstance = INSTANCE
if (tempInstance != null) {
return tempInstance
}
synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
ExpenseDatabase::class.java,
"expense_database"
).build()
INSTANCE = instance
return instance
}
}
}
}
```
5. 创建一个名为ExpenseFragment的类,用于处理用户输入并将其存储到Room数据库中。在该类中添加必要的UI元素、逻辑和Room数据库操作:
```kotlin
class ExpenseFragment : Fragment() {
private var _binding: FragmentExpenseBinding? = null
private val binding get() = _binding!!
private lateinit var expenseViewModel: ExpenseViewModel
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentExpenseBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
expenseViewModel = ViewModelProvider(this).get(ExpenseViewModel::class.java)
binding.btnSaveExpense.setOnClickListener {
val income = binding.etIncome.text.toString().toDoubleOrNull() ?: 0.0
val expenditure = binding.etExpenditure.text.toString().toDoubleOrNull() ?: 0.0
val cal = Calendar.getInstance()
val date = cal.time
val expense = Expense(date = date, income = income, expenditure = expenditure)
expenseViewModel.addExpense(expense)
clearInputs()
}
}
private fun clearInputs() {
binding.etIncome.text.clear()
binding.etExpenditure.text.clear()
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
```
6. 创建一个名为ExpenseViewModel的类,用于管理Expense对象的存储和检索。在该类中添加必要的方法和LiveData对象:
```kotlin
class ExpenseViewModel(application: Application) : AndroidViewModel(application) {
private val expenseDao: ExpenseDao
private val allExpenses: LiveData<List<Expense>>
init {
val database = ExpenseDatabase.getDatabase(application)
expenseDao = database.expenseDao()
allExpenses = expenseDao.getAllExpenses().asLiveData()
}
fun addExpense(expense: Expense) {
viewModelScope.launch {
expenseDao.addExpense(expense)
}
}
fun updateExpense(expense: Expense) {
viewModelScope.launch {
expenseDao.updateExpense(expense)
}
}
fun deleteExpense(expense: Expense) {
viewModelScope.launch {
expenseDao.deleteExpense(expense)
}
}
}
```
7. 最后,在MainActivity中添加ExpenseFragment的实例。在该类中添加必要的UI元素和逻辑代码:
```kotlin
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
setSupportActionBar(binding.toolbar)
val navController = findNavController(R.id.nav_host_fragment_content_main)
val appBarConfiguration = AppBarConfiguration(navController.graph)
setupActionBarWithNavController(navController, appBarConfiguration)
binding.fab.setOnClickListener { view ->
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.action_settings -> true
else -> super.onOptionsItemSelected(item)
}
}
override fun onSupportNavigateUp(): Boolean {
val navController = findNavController(R.id.nav_host_fragment_content_main)
return navController.navigateUp(appBarConfiguration)
|| super.onSupportNavigateUp()
}
}
```
好了,这就是使用Android Studio创建一个Fragment来允许用户输入每天的收入和支出,使用Room数据库来存储用户输入的完整步骤。
阅读全文