在回收器视图适配器android Kotlin之外更新ProgressBar
Posted
技术标签:
【中文标题】在回收器视图适配器android Kotlin之外更新ProgressBar【英文标题】:Update ProgressBar outside of recycler view adapter android Kotlin 【发布时间】:2021-12-29 03:17:29 【问题描述】:我想在回收器视图所在的父活动中更新进度条。当用户单击每个单选按钮时,我已经完成了向进度条添加一个数字,但我不知道如何将数据从回收器视图适配器传递到家长活动。
在此处输入图片说明
class MbtiQuestionAdapter(val questionList: QuestionList) :
RecyclerView.Adapter<QuestionViewHolder>()
var maps = arrayListOf<HashMap<String, String>>()
var i = 0
var e = 0
var n = 0
var t = 0
var j = 0
var p = 0
var f = 0
var s = 0
var typeQuestion = ""
var testnumbers = 0
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QuestionViewHolder
val layoutInflater = LayoutInflater.from(parent.context)
val cellForRow = layoutInflater.inflate(
AminAmix.com.socialpersonality.R.layout.question_row,
parent,
false
)
return QuestionViewHolder(cellForRow)
@SuppressLint("ResourceAsColor")
override fun onBindViewHolder(holder: QuestionViewHolder, position: Int)
//val question = questions.get(position)
if (questionList.questions[position].tip != "")
holder.view.txtTitletipsQuestionRow.visibility = View.VISIBLE
// holder.view.imgtips.visibility = View.VISIBLE
holder.view.txtTipsQuestion.visibility = View.VISIBLE
holder.view.txtTipsQuestion.text = questionList.questions[position].tip
else
holder.view.imageView15.visibility = View.INVISIBLE
holder.view.shapeBlue.visibility = View.VISIBLE
holder.view.shapeGreen.visibility = View.VISIBLE
holder.view.shapeCircle.visibility = View.VISIBLE
holder.view.txtAmountQuestion.text = questionList.questions.size.toString()
holder.view.txtCurrentQuestion.text = (position + 1).toString()
val question = questionList.questions.get(position).title
Log.i("Position", position.toString())
val answers = questionList.questions.get(position).answers
var valueOfRadio = ""
if (questionList.questions.get(position).type == "range")
holder.view.cardAB.visibility = View.INVISIBLE
for (answer in answers)
val value = answer.value
typeQuestion = answer.title
Log.i("Position2", value.toString())
if (answer.title == "Agree")
holder.view.txtQuestionDisAgree.text = answer.title
else
holder.view.txtQuestionAgree.text = answer.title
holder.view.radioGroup.setOnCheckedChangeListener group, checkedId ->
if (checkedId == AminAmix.com.socialpersonality.R.id.radioButton_middle)
Log.i("Radio", "0")
valueOfRadio = "0"
if (checkedId == AminAmix.com.socialpersonality.R.id.radioButton_agree1)
Log.i("Radio", "1")
valueOfRadio = "1"
if (checkedId == AminAmix.com.socialpersonality.R.id.radioButton_agree2)
Log.i("Radio", "2")
valueOfRadio = "2"
if (checkedId == AminAmix.com.socialpersonality.R.id.radioButton_disagree1)
Log.i("Radio", "-1")
valueOfRadio = "-1"
if (checkedId == AminAmix.com.socialpersonality.R.id.radioButton_disagree_2)
Log.i("Radio", "-2")
valueOfRadio = "-2"
val checked = group.findViewById(checkedId) as RadioButton
val list: ArrayList<String> = ArrayList()
list.add(checked.getText().toString())
Log.i("Chekkk", list.toString())
Log.i(
"checkedId", position.toString()
)
var idIf = ""
var typeIf = ""
var testValue = 0
var map = HashMap<String, String>();
var radioInt = valueOfRadio.toInt()
var selectedAnswers = questionList.questions[position].answers
if (radioInt > 0)
for (answer in selectedAnswers)
if (answer.title == "Agree")
typeIf = answer.type
testValue = answer.value
holder.view.txtQuestionDisAgree.setTextColor(Color.parseColor("#5E5E5E"));
holder.view.txtQuestionAgree.setTextColor(Color.parseColor("#B2B2B2"));
holder.view.txtCurrentQuestion.setTextColor(Color.parseColor("#0B6095"));
holder.view.txtAmountQuestion.setTextColor(Color.parseColor("#0B6095"));
holder.view.txtCurrentQuestion2.setTextColor(Color.parseColor("#0B6095"));
holder.view.txtTitleQuestions.setTextColor(Color.parseColor("#0B6095"));
holder.view.questionsTik.visibility = View.VISIBLE
else if (radioInt < 0)
for (answer in selectedAnswers)
if (answer.title == "Disagree")
typeIf = answer.type
testValue = answer.value
holder.view.txtQuestionAgree.setTextColor(Color.parseColor("#5E5E5E"));
holder.view.txtQuestionDisAgree.setTextColor(Color.parseColor("#B2B2B2"));
holder.view.txtCurrentQuestion.setTextColor(Color.parseColor("#0B6095"));
holder.view.txtAmountQuestion.setTextColor(Color.parseColor("#0B6095"));
holder.view.txtCurrentQuestion2.setTextColor(Color.parseColor("#0B6095"));
holder.view.txtTitleQuestions.setTextColor(Color.parseColor("#0B6095"));
holder.view.questionsTik.visibility = View.VISIBLE
else
holder.view.txtQuestionAgree.setTextColor(Color.parseColor("#B2B2B2"));
holder.view.txtQuestionDisAgree.setTextColor(Color.parseColor("#B2B2B2"));
holder.view.txtCurrentQuestion.setTextColor(Color.parseColor("#0B6095"));
holder.view.txtAmountQuestion.setTextColor(Color.parseColor("#0B6095"));
holder.view.txtCurrentQuestion2.setTextColor(Color.parseColor("#0B6095"));
holder.view.txtTitleQuestions.setTextColor(Color.parseColor("#0B6095"));
holder.view.questionsTik.visibility = View.VISIBLE
var absolutResultRadio = Math.abs(valueOfRadio.toInt())
// map["Q" + "_" + idIf.toString() + "_" + typeIf.toString()] = valueOfRadio
map["Q" + (position + 1).toString()] =
typeIf.toString() + "_" + absolutResultRadio * testValue
var con = maps.any it.containsKey("Q" + (position + 1).toString())
if (maps.any con == true ) // filter
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
maps.removeIf it.containsKey("Q" + (position + 1))
testnumbers = testnumbers - 1
testnumbers = testnumbers + 1
maps.add(map)
Log.i("maps", "in dare ejra mishe")
else
maps.add(map)
testnumbers = testnumbers + 1
Log.i ( "testnumber2" , testnumbers.toString())
else
holder.view.cardRange.visibility = View.INVISIBLE
holder.view.radioButtonFirstAAndB.text = answers[0].title
holder.view.radioButtonSecondAAndB.text = answers[1].title
holder.view.radioGroup2.setOnCheckedChangeListener group, checkedId ->
if (checkedId == AminAmix.com.socialpersonality.R.id.radioButtonFirstAAndB)
Log.i("Radio", "1")
valueOfRadio = "1"
if (checkedId == AminAmix.com.socialpersonality.R.id.radioButtonSecondAAndB)
Log.i("Radio", "-1")
valueOfRadio = "-1"
val checked = group.findViewById(checkedId) as RadioButton
val list: ArrayList<String> = ArrayList()
list.add(checked.getText().toString())
Log.i("Chekkk", list.toString())
Log.i(
"checkedId", position.toString()
)
var idIf = ""
var typeIf = ""
var testValue = 0
var map = HashMap<String, String>();
var radioInt = valueOfRadio.toInt()
var selectedAnswers = questionList.questions[position].answers
if (radioInt > 0)
typeIf = selectedAnswers[0].type
testValue = selectedAnswers[0].value
holder.view.txtCurrentQuestion.setTextColor(Color.parseColor("#0B6095"));
holder.view.txtAmountQuestion.setTextColor(Color.parseColor("#0B6095"));
holder.view.txtCurrentQuestion2.setTextColor(Color.parseColor("#0B6095"));
holder.view.txtTitleQuestions.setTextColor(Color.parseColor("#0B6095"));
holder.view.questionsTik.visibility = View.VISIBLE
else if (radioInt < 0)
typeIf = selectedAnswers[1].type
testValue = selectedAnswers[1].value
holder.view.txtCurrentQuestion.setTextColor(Color.parseColor("#0B6095"));
holder.view.txtAmountQuestion.setTextColor(Color.parseColor("#0B6095"));
holder.view.txtCurrentQuestion2.setTextColor(Color.parseColor("#0B6095"));
holder.view.txtTitleQuestions.setTextColor(Color.parseColor("#0B6095"));
holder.view.questionsTik.visibility = View.VISIBLE
var absolutResultRadio = Math.abs(valueOfRadio.toInt())
// map["Q" + "_" + idIf.toString() + "_" + typeIf.toString()] = valueOfRadio
map["Q" + (position + 1).toString()] =
typeIf.toString() + "_" + absolutResultRadio * testValue
var con = maps.any it.containsKey("Q" + (position + 1).toString())
if (maps.any con == true ) // filter
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
maps.removeIf it.containsKey("Q" + (position + 1))
maps.add(map)
Log.i("maps", "in dare ejra mishe")
else
maps.add(map)
Log.i("mapSize", maps.toString())
Log.i("mapSize", maps.size.toString())
if (maps.size.toInt() == questionList.questions.size
)
Log.i("maps", "Halaaaaaaaaaaa in dare ejra mishe")
Log.i("Mapss", "SomeText: " + Gson().toJson(maps))
val dataOfTestToJson = Gson().toJson(maps).toString()
val eRegex = Regex("E_(\\d+)")
val iRegex = Regex("I_(\\d+)")
val sRegex = Regex("S_(\\d+)")
val nRegex = Regex("N_(\\d+)")
val fRegex = Regex("F_(\\d+)")
val tRegex = Regex("T_(\\d+)")
val pRegex = Regex("P_(\\d+)")
val jRegex = Regex("J_(\\d+)")
e = eRegex.findAll(dataOfTestToJson).map it.groupValues[1].toInt() .sum()
i = iRegex.findAll(dataOfTestToJson).map it.groupValues[1].toInt() .sum()
s = sRegex.findAll(dataOfTestToJson).map it.groupValues[1].toInt() .sum()
n = nRegex.findAll(dataOfTestToJson).map it.groupValues[1].toInt() .sum()
f = fRegex.findAll(dataOfTestToJson).map it.groupValues[1].toInt() .sum()
t = tRegex.findAll(dataOfTestToJson).map it.groupValues[1].toInt() .sum()
p = pRegex.findAll(dataOfTestToJson).map it.groupValues[1].toInt() .sum()
j = jRegex.findAll(dataOfTestToJson).map it.groupValues[1].toInt() .sum()
val data = JSONObject()
data.put("E", e)
data.put("I", i)
data.put("S", s)
data.put("N", n)
data.put("T", t)
data.put("F", f)
data.put("J", j)
data.put("P", p)
Log.i(
"dataSexy",
data.toString()
)
Log.i(
"mapsSexy",
"I = $i" + " " + "E = $e" + " " + "S= $s" + " " + "N = $n" + " " + "F = $f" + " " + "T = $t" + " " + "P = $p" + " " + "J = $j"
)
val context = holder.view.context
val intent = Intent(context, LoadingMbtiActivity::class.java)
intent.putExtra("e", e.toString())
intent.putExtra("i", i.toString())
intent.putExtra("s", s.toString())
intent.putExtra("n", n.toString())
intent.putExtra("f", f.toString())
intent.putExtra("t", t.toString())
intent.putExtra("p", p.toString())
intent.putExtra("j", j.toString())
intent.putExtra("data", data.toString())
context.startActivity(intent)
(context as Activity).finish()
holder.view.txtQuestionInRow.text = question
override fun getItemCount(): Int
return questionList.questions.size
override fun getItemViewType(position: Int): Int
return position
class QuestionViewHolder(val view: View) : RecyclerView.ViewHolder(view)
tps://i.stack.imgur.com/aQiS4.png
class MBTITEST : AppCompatActivity()
lateinit var token: String
override fun onCreate(savedInstanceState: Bundle?)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_mbtitest)
window.statusBarColor = ContextCompat.getColor(this, R.color.black)
val preferences: SharedPreferences =
applicationContext.getSharedPreferences("SOCIAL_PERSONALITY", Context.MODE_PRIVATE)
token = preferences.getString("TOKEN", null).toString() //second parameter default value.
var tokenBAr = "Bearer $token"
getQuestions(tokenBAr)
fun getQuestions(token: String)
val apilnterface: APIInterface = APIClient().getClient()!!.create(APIInterface::class.java)
var call: Call<QuestionList> = apilnterface.getQuestions(token)
call.enqueue(object : Callback<QuestionList>
override fun onResponse(
call: Call<QuestionList>,
response: Response<QuestionList>
)
if (response.code() == 200)
// Toast.makeText(
// this@MBTITEST,
// "Testatol GolMohammadi",
// Toast.LENGTH_LONG
// )
// .show()
// Log.w("RESGetID", "$response.body().toString()")
val dataFromResponse = response.body()
val questionList = dataFromResponse?.questions
val size = questionList?.size
val title = questionList?.get(0)?.title
print(questionList)
Log.w("QuestionListDaDa", questionList.toString())
Log.w("QuestionListDaDa", size.toString())
Log.w("QuestionListDaDa", title.toString())
runOnUiThread
val layoutManager = LinearLayoutManager(
this@MBTITEST,
LinearLayoutManager.HORIZONTAL,
false
)
recycler_questions.layoutManager = layoutManager
recycler_questions.setHasFixedSize(true)
recycler_questions.adapter?.setHasStableIds(true)
Collections.shuffle(dataFromResponse?.questions)
recycler_questions.adapter =
dataFromResponse?.let MbtiQuestionAdapter(it)
txtCountTotal.text = questionList?.size.toString()
var mbtiAdapter = dataFromResponse?.let MbtiQuestionAdapter(it)
var testnumbers = mbtiAdapter?.testnumbers
textView15.setText(testnumbers.toString())
Log.i("testnumber", testnumbers.toString())
// btnShowRes.setOnClickListener
// // dataFromResponse?.let MbtiQuestionAdapter(it) ?.activateButtons(true)
// val intent = Intent(this@MBTITEST, ShowTestResultActivity::class.java)
// startActivity(intent)
// finish()
//
if (response.code() == 400)
try
val jObjError = JSONObject(response.errorBody()!!.string())
Toast.makeText(
applicationContext,
jObjError.getString("message"),
Toast.LENGTH_LONG
).show()
catch (e: Exception)
Toast.makeText(applicationContext, e.message, Toast.LENGTH_LONG).show()
if (response.code() == 401)
try
val preferences: SharedPreferences =
applicationContext.getSharedPreferences(
"SOCIAL_PERSONALITY",
Context.MODE_PRIVATE
)
preferences.edit().putString("TOKEN", "").apply()
val jObjError = JSONObject(response.errorBody()!!.string())
Toast.makeText(
applicationContext,
jObjError.getString("message"),
Toast.LENGTH_LONG
).show()
catch (e: Exception)
Toast.makeText(applicationContext, e.message, Toast.LENGTH_LONG).show()
val intent = Intent(this@MBTITEST, FirstPageActivity::class.java)
startActivity(intent)
finish()
override fun onFailure(call: Call<QuestionList>, t: Throwable)
Toast.makeText(
this@MBTITEST,
" Register is not ok",
Toast.LENGTH_LONG
)
.show()
)
【问题讨论】:
您可以使用接口或作为构造函数参数传递的 lambda 回调将事件从适配器发送到活动。在问题中添加您当前的适配器和 MainActivity 代码。 谢谢阿皮特。我想将 testNumber 从适配器传递到 MbtiActivity 你想什么时候通过呢?就像它的值发生变化或在某些点击事件或其他事件之后发生的变化一样? 另外,您已将整个课程粘贴到此处。您可以编辑您的问题以仅保留相关部分吗? @ArpitShukla 我想每当适配器中的值更改时自动向进度条添加一个数字。我是新来的,听到你建议什么样的改变? 【参考方案1】:就像@Arpit Shukla 提到的那样,您可以使用 lambda 或函数在适配器和活动之间传递数据
将函数作为参数添加到适配器的构造函数
class MbtiQuestionAdapter(val questionList: QuestionList,val onRadioButtonClick : (Int) -> Unit)
在你的活动中定义一个函数来更新你的进度条,它需要一个数字作为参数或任何你想要的
private fun updateProgressBar(testNumber : Int)
//update progress bar
在初始化时将上述函数传递给适配器构造函数
recycler_questions.adapter = dataFromResponse?.let MbtiQuestionAdapter(it)number -> updateProgressBar(number)
当您想将数字传递给您的活动时,最后在您的适配器中调用 onRadioButtonClick
onRadioButtonClick(number)
【讨论】:
我还有一个问题,如果我想当用户点击适配器中的所有单选按钮时显示一个按钮,并且当用户触摸它时意图产生活动。你的解决方案是什么? @Zibfit 我不明白你真正想要做什么,你能说得更详细些吗 如代码所示,我这里有很多项。用户通过单击每个单选按钮来确定已留下一个项目。现在我希望在单击所有项目时在所有项目下显示一个按钮。 您可以在 ativity 中添加另一个函数,显示您想要的按钮,并在单击所有项目时在适配器中调用它以上是关于在回收器视图适配器android Kotlin之外更新ProgressBar的主要内容,如果未能解决你的问题,请参考以下文章
如何通过 android 中的回收器视图运行 for 循环?