簡體   English   中英

Android:將新項目添加到列表並使用 Kotlin 通過 RecyclerView 適配器顯示

[英]Android: add a new item to a list and display it via RecyclerView adapter using Kotlin

我有一個帶有 RecyclerView 的片段。 當用戶單擊片段中的按鈕(添加新項目)時,應用程序會將用戶(通過意圖)帶到一個表單以填寫一些數據。

當我單擊 (ADD ITEM) 時,它應該將數據添加到數組列表並完成該屏幕。 回到片段之后,應該使用適配器將這些數據添加到 RecyclerView 中。

這是我的代碼:

這是片段:

private val REQUEST_CODE = 2

internal lateinit var adapter: ShipmentItemAdapter

override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {

    return inflater!!.inflate(R.layout.fragment_step_three_shipment, container, false)
}

override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    btnAddNewShipmentStep3.setOnClickListener {
        val intent = Intent(context, AddItemActivity::class.java)
        startActivityForResult(intent, REQUEST_CODE)
    }
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data);

    val items = ArrayList<ItemsItem>()

    if (requestCode == REQUEST_CODE) {

        adapter = ShipmentItemAdapter(context, items)

        if (resultCode == Activity.RESULT_OK) {
            itemsShipments.visibility = View.VISIBLE
            itemsShipments.layoutManager = LinearLayoutManager(context)
            itemsShipments.setHasFixedSize(true)
            itemsShipments.adapter = adapter

        } else if (resultCode == Activity.RESULT_CANCELED) {
            itemsShipments.visibility = View.GONE
        }
    }
}

這是活動:

class AddItemActivity : AppCompatActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_add_item_form)

    linPackageAddShipment.setOnClickListener {
        edtPackageAddShipment.requestFocus()
    }

    linPiecesAddShipment.setOnClickListener {
        edtPiecesAddShipment.requestFocus()
    }

    linWeightAddShipment.setOnClickListener {
        edtWeightAddShipment.requestFocus()
    }

    linDescriptionAddShipment.setOnClickListener {
        edtDescriptionAddShipment.requestFocus()
    }


    btnAddItemAddShipment.setOnClickListener {
        val errors = collectData()

        collectData()

        if (errors.isEmpty()) {

            val intent = Intent()
            setResult(Activity.RESULT_OK, intent)
            finish()

        } else {
            val errorBody = errors.map { getString(it) }.joinToString("\n") { it }
            MaterialDialog.Builder(this)
                    .title("Oops")
                    .content(errorBody)
                    .positiveText(R.string.ok)
                    .positiveColor(ContextCompat.getColor(this, R.color.colorPrimary))
                    .onAny({ dialog, _ -> dialog.dismiss() })
                    .show()
        }
    }
  }

  private fun collectData(): ArrayList<Int> {
    val errors = ArrayList<Int>()
    val item = ItemsItem()

    if (edtPackageAddShipment.text.toString().isEmpty()) {
        errors.add(R.string.packages_must_not_be_empty)

    } else {
        item.numberOfPackages = edtPackageAddShipment.text.toString().toInt()
    }

    if (edtPiecesAddShipment.text.toString().isEmpty()) {
        errors.add(R.string.pieces_must_not_be_empty)

    } else {
        item.numberOfPieces = edtPiecesAddShipment.text.toString()
    }

    if (edtWeightAddShipment.text.toString().isEmpty()) {
        errors.add(R.string.weight_must_not_be_empty)

    } else {
        item.weightUnit = edtWeightAddShipment.text.toString().toInt()
    }

    if (edtHeightAddShipment.text.toString().isEmpty()) {
        errors.add(R.string.height_must_not_be_empty)

    } else {
        item.height = edtHeightAddShipment.text.toString()
    }

    if (edtWidthAddShipment.text.toString().isEmpty()) {
        errors.add(R.string.width_must_not_be_empty)

    } else {
        item.width = edtWidthAddShipment.text.toString()
    }
    if (edtLengthAddShipment.text.toString().isEmpty()) {
        errors.add(R.string.length_must_not_be_empty)

    } else {
        item.length = edtLengthAddShipment.text.toString()
    }

    if (edtDescriptionAddShipment.text.toString().isEmpty()) {
        errors.add(R.string.description_must_not_be_empty)

    } else {
        item.description = edtDescriptionAddShipment.text.toString()
    }

    CreateNewShipmentActivity.mainShipment.shipmentObj.items?.add(item)

    return errors
  }

  override fun onBackPressed() {
    setResult(Activity.RESULT_CANCELED)
    super.onBackPressed()
  }
}

這是適配器:

class ShipmentItemAdapter internal constructor(private val context: Context, private val items: List<ItemsItem>) : RecyclerView.Adapter<ShipmentItemAdapter.MyViewHolder>() {

  private val inflater: LayoutInflater = LayoutInflater.from(context)


  override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
    val view = inflater.inflate(R.layout.item_shipment_package, parent, false)

    return MyViewHolder(view).listen { pos, type ->
        val item = items[pos]
        val intent = Intent(context, AddItemActivity::class.java)
        startActivity(context, intent, null)
    }
  }


  override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
    holder.namePackageShipmentPackage.text = items[position].description
    holder.quantityPackageShipmentPackage.text = items[position].description
    holder.dimensionPackageHeightShipmentPackage.text = items[position].description
    holder.dimensionPackageWidthShipmentPackage.text = items[position].description
    holder.dimensionPackageLengthShipmentPackage.text = items[position].description

  }

  override fun getItemCount(): Int {
    return items.size
  }

  inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

    var namePackageShipmentPackage: AppCompatTextView = itemView.findViewById(R.id.namePackageShipmentPackage)
    var quantityPackageShipmentPackage: AppCompatTextView = itemView.findViewById(R.id.quantityPackageShipmentPackage)
    var dimensionPackageHeightShipmentPackage: AppCompatTextView = itemView.findViewById(R.id.dimensionPackageHeightShipmentPackage)
    var dimensionPackageWidthShipmentPackage: AppCompatTextView = itemView.findViewById(R.id.dimensionPackageWidthShipmentPackage)
    var dimensionPackageLengthShipmentPackage: AppCompatTextView = itemView.findViewById(R.id.dimensionPackageLengthShipmentPackage)


  }

  private fun <T : RecyclerView.ViewHolder> T.listen(event: (position: Int, type: Int) -> Unit): T {
    itemView.setOnClickListener {
        event.invoke(adapterPosition, itemViewType)
    }
    return this
  }

這些是對象模型:

class ShipmentObj {
    var items: ArrayList<ItemsItem?>? = null
}


data class ItemsItem(
    var numberOfPieces: String? = null,
    var length: String? = null,
    var description: String? = null,
    var numberOfPackages: Int? = null,
    var number: Int? = null,
    var width: String? = null,
    var height: String? = null,
    var weightUnit: Int? = null
)

當我嘗試添加新項目時,片段中沒有顯示任何內容! 我現在不知道錯在哪里?

謝謝。

您需要首先在您的適配器中添加一個用於向 Array 添加新項目的函數,在您的情況下是“項目:列表”:

第一步:

  • 在您的適配器 ShipmentItemAdapter 中添加下一個樂趣

 fun addNewItem(itemsNew: List<ItemsItem>){ items.clear() // ->> optional if you need have clear of object items.addAll(itemsNew) notifyDataSetChanged() }

然后,在 onActivityResult 的片段中,當您收到 Activity.RESULT_OK 時,您可能會添加新項目

 adapter.addNewItem(itemsNew)

在 onActivityResult 你可以看到你的代碼中的錯誤你做這樣的事情

val items = ArrayList<ItemsItem>()
adapter = ShipmentItemAdapter(context, items)

您為適配器分配了一個空的項目列表。 如果我沒猜錯,您也不會傳遞您要發送的項目。

 if (errors.isEmpty()) {
        val intent = Intent()
        setResult(Activity.RESULT_OK, intent)
        finish()
 }

結果您完成了活動而沒有傳遞任何項目。 之前的活動沒有收到任何東西。 我無法執行您的代碼,因為我沒有執行它的所有元素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM