简体   繁体   English

Android:将新项目添加到列表并使用 Kotlin 通过 RecyclerView 适配器显示

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

I have a fragment that has a RecyclerView.我有一个带有 RecyclerView 的片段。 When the user clicks a button (ADD NEW ITEM) in the fragment, the app takes the user (via intent) to a form to fill-in some data.当用户单击片段中的按钮(添加新项目)时,应用程序会将用户(通过意图)带到一个表单以填写一些数据。

When I click on (ADD ITEM), it should add the data to the array list and finish that screen.当我单击 (ADD ITEM) 时,它应该将数据添加到数组列表并完成该屏幕。 After going back to the fragment, this data should be added to the RecyclerView using the adapter.回到片段之后,应该使用适配器将这些数据添加到 RecyclerView 中。

This is my code:这是我的代码:

Here is the fragment:这是片段:

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
        }
    }
}

And here is the activity:这是活动:

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()
  }
}

Here is the adapter:这是适配器:

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
  }

These are the object model:这些是对象模型:

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
)

When I try to add new item nothing is showing in the fragment!当我尝试添加新项目时,片段中没有显示任何内容! I don't now where is the mistake?我现在不知道错在哪里?

Thanks.谢谢。

You need to add first in your adapter one function for adding new items to Array, in your case is "items: List":您需要首先在您的适配器中添加一个用于向 Array 添加新项目的函数,在您的情况下是“项目:列表”:

First step:第一步:

  • In your adapter ShipmentItemAdapter add the next fun在您的适配器 ShipmentItemAdapter 中添加下一个乐趣

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

then, in your fragment in onActivityResult when you receive the Activity.RESULT_OK you might add the new item然后,在 onActivityResult 的片段中,当您收到 Activity.RESULT_OK 时,您可能会添加新项目

 adapter.addNewItem(itemsNew)

In the onActivityResult you can see the error in your code You do something like this在 onActivityResult 你可以看到你的代码中的错误你做这样的事情

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

You assign to the adapter, an empty list of items.您为适配器分配了一个空的项目列表。 And if i'm not wrong, you don't pass the item that you want to send either.如果我没猜错,您也不会传递您要发送的项目。

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

You finish the activity without passing any item as a result.结果您完成了活动而没有传递任何项目。 The previous activity doesn't receive anything.之前的活动没有收到任何东西。 I can't execute you code because I don't have all the elements to execute it.我无法执行您的代码,因为我没有执行它的所有元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Android,Kotlin:Recyclerview,如何防止显示最后一项,但将其传递给适配器 - Android, Kotlin: Recyclerview, how to prevent the last item to be shown, but pass it to the adapter Android RecyclerView:如何将新项目添加到列表顶部? - Android RecyclerView: how to add new item to top of list? 使用适配器在android中显示列表仅显示第一项 - display of a list in android using adapter shows only first item android kotlin - 如何将点击监听器添加到 RecyclerView 适配器 - android kotlin -how to add click listener to RecyclerView adapter Android RecyclerView 未连接适配器(Kotlin) - Android RecyclerView No adapter attached (Kotlin) 如何在列表中添加新项目时更新 RecyclerView 适配器数据 - How to update RecyclerView Adapter Data while adding new item in List 如何使用 Kotlin 在 RecyclerView 中显示所选项目的项目信息 - How to display item info on selected item in RecyclerView using Kotlin 如何使用 kotlin 从 android 适配器 recyclerview 拨打电话 - how to make a phone call from android adapter recyclerview using kotlin 在收到Firebase消息时在RecyclerView Adapter中添加列表项 - Add list item in RecyclerView Adapter on receiving Firebase message Android工具在列表项上单击以通过自定义列表适配器将数据传递到新的活动 - Android implement on list item click to pass data to new Activity via custom list adapter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM