我是Android的新手,还没有完全掌握它的概念。 我试图在我从https://www.raywenderlich.com/category/android(一个非常简单的提醒应用程序 - 它显示一个字符串列表作为提醒)的教程中进行更改。 MainActivity的代码是:
package com.example.reminderapp
import android.app.Activity
import android.app.AlertDialog
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.res.Configuration
import java.text.SimpleDateFormat
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*
class MainActivity : AppCompatActivity() {
private val taskList: MutableList<Task> = mutableListOf()
private val taskListDesciptors: MutableList<String> = mutableListOf()
private val adapter by lazy { makeAdapter(taskListDesciptors) }
//private val adapter by lazy { makeAdapterTask(taskList) }
private val tickReceiver by lazy { makeBroadcastReceiver() }
private val ADD_TASK_REQUEST = 1
private val PREFS_TASKS = "prefs_tasks"
private val KEY_TASKS_LIST = "tasks_list"
companion object {
private const val LOG_TAG = "MainActivityLog"
private fun getCurrentTimeStamp(): String {
val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US)
val now = Date()
return simpleDateFormat.format(now)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
taskListView.adapter = adapter
taskListView.onItemClickListener = AdapterView.OnItemClickListener { parent, view, position, id -> }
val savedList = getSharedPreferences(PREFS_TASKS, Context.MODE_PRIVATE).getString(KEY_TASKS_LIST, null)
if (savedList != null) {
val items = savedList.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
//taskList.addAll(items)
}
taskListView.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ ->
taskSelected(position)
}
}
override fun onResume() {
// 1
super.onResume()
// 2
dateTimeTextView.text = getCurrentTimeStamp()
// 3
registerReceiver(tickReceiver, IntentFilter(Intent.ACTION_TIME_TICK))
}
override fun onPause() {
// 4
super.onPause()
// 5
try {
unregisterReceiver(tickReceiver)
} catch (e: IllegalArgumentException) {
Log.e(MainActivity.LOG_TAG, "Time tick Receiver not registered", e)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
// 1
if (requestCode == ADD_TASK_REQUEST) {
// 2
if (resultCode == Activity.RESULT_OK) {
// 3
//val task = data?.getStringExtra(TaskDescriptionActivity.EXTRA_TASK_DESCRIPTION)
val task = data?.getSerializableExtra(TaskDescriptionActivity.EXTRA_TASK_DESCRIPTION) as Task
task?.let {
taskList.add(task)
taskListDesciptors.add(task.taskDescription) // TODO: WHY DO I NEED THIS?!
// 4
adapter.notifyDataSetChanged()
}
//adapter.notifyDataSetChanged()
}
}
}
override fun onStop() {
super.onStop()
// Save all data which you want to persist.
val savedList = StringBuilder()
for (task in taskList) {
savedList.append(task)
savedList.append(",")
}
getSharedPreferences(PREFS_TASKS, Context.MODE_PRIVATE).edit()
.putString(KEY_TASKS_LIST, savedList.toString()).apply()
}
override fun onConfigurationChanged(newConfig: Configuration?) {
super.onConfigurationChanged(newConfig)
}
fun addTaskClicked(view: View) {
val intent = Intent(this, TaskDescriptionActivity::class.java)
startActivityForResult(intent, ADD_TASK_REQUEST)
}
private fun TasksListToDescriptionsList(list: List<Task>) : List<String>{
val retMutableList: MutableList<String> = mutableListOf()
for (task in list) {
retMutableList.add(task.taskDescription)
}
val retList: List<String> = retMutableList
return retList
}
private fun makeAdapter(list: List<String>): ArrayAdapter<String> {
return ArrayAdapter(this, android.R.layout.simple_list_item_1, list)
}
private fun makeAdapterTask(list: List<Task>): ArrayAdapter<String> {
return ArrayAdapter(this, android.R.layout.simple_list_item_1, TasksListToDescriptionsList(list))
}
private fun makeBroadcastReceiver(): BroadcastReceiver {
return object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent?) {
if (intent?.action == Intent.ACTION_TIME_TICK) {
dateTimeTextView.text = getCurrentTimeStamp()
}
}
}
}
private fun taskSelected(position: Int) {
// 1
AlertDialog.Builder(this)
// 2
.setTitle(R.string.alert_title)
// 3
.setMessage(taskList[position].taskDescription)
.setPositiveButton(R.string.delete, { _, _ ->
taskList.removeAt(position)
taskListDesciptors.removeAt(position)
adapter.notifyDataSetChanged()
})
.setNegativeButton(R.string.cancel, {
dialog, _ -> dialog.cancel()
})
// 4
.create()
// 5
.show()
}
}
我的问题涉及第private val adapter by lazy { makeAdapter(taskListDesciptors) }
行和private val adapter by lazy { makeAdapter(taskList) }
行。 taskListDesciptors是一个字符串列表,taskList是另一个文件中声明的对象列表:
public class Task (description: String, date: Date) : Serializable {
val taskDescription = description
val dateTime = date
}
如果我使用private val adapter by lazy { makeAdapter(taskListDesciptors) }
,则ListView每次都会更新,但如果我使用private val adapter by lazy { makeAdapter(taskList) }
则不会更新。
我错过了什么?
感谢!
探