核心代碼:activity
class MainActivity : AppCompatActivity() {
var codeAdapter: CodeAdapter? = null
var count: Int = 1
var stringSparseArray: SparseArray<String>? = null
var mPosition :Int = -1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
stringSparseArray = SparseArray()
rv_code_list.layoutManager = LinearLayoutManager(this)
codeAdapter = CodeAdapter(count, this,stringSparseArray!!)
rv_code_list.adapter = codeAdapter
btn_add.setOnClickListener {
++count
codeAdapter!!.setData(count,stringSparseArray!!)
}
ItemClickSupport.addTo(rv_code_list).addOnChildClickListener(R.id.iv_scan, object : ItemClickSupport.OnChildClickListener {
override fun onChildClicked(recyclerView: RecyclerView, position: Int, v: View) {
mPosition = position
startActivityForResult<SecondActivity>(888)
}
})
ItemClickSupport.addTo(rv_code_list).addOnChildClickListener(R.id.btn_delete, object : ItemClickSupport.OnChildClickListener {
override fun onChildClicked(recyclerView: RecyclerView, position: Int, v: View) {
mPosition = position
codeAdapter!!.removeData(mPosition,stringSparseArray!!)
if (count >0){
--count
}
}
})
}
@SuppressLint("MissingSuperCall")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (data != null) {
if (resultCode == Activity.RESULT_OK) {
val code = when (requestCode) {
888 -> data.getStringExtra("data")
889 -> data.getStringExtra("data")//批量唯一碼
else -> null
}
stringSparseArray!!.put(mPosition,code)
codeAdapter!!.setData(stringSparseArray!!,mPosition)
}
}
}
}
Adapter
class CodeAdapter(var count: Int, val context: Context,var mStringSparseArray: SparseArray<String>) : RecyclerView.Adapter<CodeAdapter.InnerHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): InnerHolder {
//加載view
val view: View = LayoutInflater.from(context).inflate(R.layout.recycleview_item_delete, parent, false)
return InnerHolder(view)
}
override fun getItemCount(): Int {
return count
}
fun setData(stringSparseArray: SparseArray<String>, index: Int) {
mStringSparseArray = stringSparseArray
notifyItemChanged(index)
}
fun setData( mCount: Int,stringSparseArray: SparseArray<String>) {
count = mCount
mStringSparseArray = stringSparseArray
//添加動畫
notifyItemInserted(mCount -1)
// notifyDataSetChanged()
}
// 刪除數據
fun removeData(position: Int,stringSparseArray: SparseArray<String>) {
mStringSparseArray = stringSparseArray
mStringSparseArray.delete(position)
if (count>0){
--count
}
notifyItemRemoved(position)
notifyDataSetChanged()
}
override fun onBindViewHolder(holder: InnerHolder, position: Int) {
holder.itemText.setText( mStringSparseArray[position])
}
class InnerHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var itemText: EditText = itemView.findViewById(R.id.et_unique_num)
}
}