Я хочу развернуть новые элементы в RecyclerView, в то время как ранее развернутые элементы должны автоматически сворачиваться.
Что у меня есть готово >>
Элементы раскрываются и сворачиваются при нажатии; однако они не сворачиваются автоматически при раскрытии другого элемента.
image1
На самом деле я хочу сделать это >>
Когда один элемент разворачивается, любой ранее развернутый элемент должен автоматически сворачиваться.
image2
Что я исследовал h1>
- Из этого переполнения стека получается то, что мне нужно, но Я не уверен, как это перевести на Kotlin. Насколько я понимаю, он сохраняет предыдущую позицию, а затем сравнивает ее с текущей позицией, используя оператор If-Else для принятия решения и выполнения действия.
- Есть еще одно переполнение стека, оно тоже из Java; У меня есть некоторое представление об этом и базовое понимание общей концепции, но я не могу полностью объяснить это себе построчно.
< li>Этот образец на Github. Он полностью соответствует моим потребностям, но стиль кода довольно сложен и недостаточно гибок, чтобы я мог добавлять другие функции и дизайн.
- Почему предыдущая позиция должна быть -1?
- Как следует разделить currentPosition и previousPosition и сохранить previousPosition в другом объекте и значении?
< li>Если предыдущая позиция работоспособна, как мне ее реализовать в своем проекте? - Если доступно, можете поделиться со мной соответствующими ресурсами?
например: снимок экрана с частью примера кода или другими ресурсами
Код
h1>
product_list_item.kt
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.android.volley.Request
import com.android.volley.RequestQueue
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.Volley
import com.google.android.material.floatingactionbutton.FloatingActionButton
import org.json.JSONArray
import org.json.JSONObject
class ViewPartActivity : AppCompatActivity() {
private lateinit var newRecylerview : RecyclerView
private lateinit var newArrayList : ArrayList
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_view_part)
val btnInsertView: FloatingActionButton = findViewById(R.id.btnInsertView)
btnInsertView.setOnClickListener {
val insertViewIntent = Intent(this, AddPartActivity::class.java)
startActivity(insertViewIntent)
}
getData()
}
private fun getData() {
val url = "WEBAPI"
val requestQueue: RequestQueue = Volley.newRequestQueue(this)
val jsonObjectRequest: JsonObjectRequest = JsonObjectRequest(Request.Method.GET, url, null,
{ response ->
val jsonArray: JSONArray = response.getJSONArray("tbl_product")
val namelist = ArrayList()
val categorylist = ArrayList()
val quantitylist = ArrayList()
val pricelist = ArrayList()
for (x in 0 until jsonArray.length()) {
val jsonObject: JSONObject = jsonArray.getJSONObject(x)
val name: String = jsonObject.getString("NAME")
val category: String = jsonObject.getString("CATOGORYID")
val quantity: String = jsonObject.getString("QUANTITY")
val price: String = jsonObject.getString("PRICE")
namelist.add(name)
categorylist.add(category)
quantitylist.add(quantity)
pricelist.add(price)
}
newRecylerview =findViewById(R.id.recyclerView)
newRecylerview.layoutManager = LinearLayoutManager(this)
newRecylerview.setHasFixedSize(true)
newArrayList = arrayListOf()
for(i in namelist.indices){
val product = Product(namelist,categorylist,quantitylist,pricelist)
newArrayList.add(product)
}
val adapter = ProductAdapter(newArrayList)
newRecylerview.adapter = adapter
}, { error ->
Toast.makeText(this, error.message, Toast.LENGTH_LONG).show()
})
requestQueue.add(jsonObjectRequest)
}
}
ProductAdapter.kt
class ProductAdapter(private val productList : ArrayList) : RecyclerView.Adapter() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.product_list_item, parent,false)
return MyViewHolder(itemView)
}
@SuppressLint("SetTextI18n")
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val currentItem = productList[position]
holder.tvProductName.text = currentItem.name
holder.tvProductCategory.text= currentItem.category
holder.tvProductQuantity.text=currentItem.quantity
holder.tvProductPrice.text= "RM "+currentItem.price
val isVisible : Boolean = currentItem.visibility
holder.constraintLayout.visibility = if (isVisible) View.VISIBLE else View.GONE
holder.tvProductName.setOnClickListener{
currentItem.visibility =!currentItem.visibility
notifyItemChanged(position)
}
}
override fun getItemCount(): Int {
return productList.size
}
class MyViewHolder(itemView : View) : RecyclerView.ViewHolder(itemView) {
val tvProductName: TextView = itemView.findViewById(R.id.productName)
val tvProductCategory : TextView = itemView.findViewById(R.id.productCategory)
val tvProductQuantity : TextView = itemView.findViewById(R.id.productQuantity)
val tvProductPrice : TextView = itemView.findViewById(R.id.productPrice)
val constraintLayout : ConstraintLayout = itemView.findViewById(R.id.expandedLayout)
}
}
Product.kt
data class Product(
var name: String, var category: String, var quantity: String, var price: String, var visibility: Boolean = false
)
Подробнее здесь: https://stackoverflow.com/questions/696 ... cyclerview
Мобильная версия