Как изменить значение Textview, присутствующего в другом действии, если значение Textview в моем текущем действии меняетAndroid

Форум для тех, кто программирует под Android
Ответить Пред. темаСлед. тема
Anonymous
 Как изменить значение Textview, присутствующего в другом действии, если значение Textview в моем текущем действии меняет

Сообщение Anonymous »

Итак, у меня есть два действия с именем «MainActivity» и действие с именем «Second», поэтому у моего MainActivity есть собственный класс адаптера с именем «PractiseAdapter». Итак, моя MainActivity содержит Textview с идентификатором
"textCount" и recyclerview с именем "recyclerView" и кнопку "btnGo". Кнопка используется для перехода к другому действию «Второе». Поэтому, когда я нажимаю на Cardview, присутствующий в recyclerview, мой счетчик «textCount» продолжает увеличиваться на 1. Ниже приведен код моего MainActivity.kt

Код: Выделить всё

import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView

class MainActivity : AppCompatActivity() {

private lateinit var textCount:TextView
@SuppressLint("MissingInflatedId")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)

val recyclerView = findViewById(R.id.recyclerview)
textCount = findViewById(R.id.textCount)
val btnGo = findViewById(R.id.btnGo)

val cards = listOf("Item1")

// Load the saved text count
loadTextCount()

val adapter = PractiseAdapter(cards,textCount)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = adapter

btnGo.setOnClickListener {
val intent = Intent(this@MainActivity,Second::class.java)
startActivity(intent)
}

}

private fun saveTextCount(count: Int) {
val sharedPreferences: SharedPreferences = getSharedPreferences("MyPrefs", MODE_PRIVATE)
val editor = sharedPreferences.edit()
editor.putInt("textCount", count)
editor.apply() // or editor.commit()
}

private fun loadTextCount() {
val sharedPreferences: SharedPreferences = getSharedPreferences("MyPrefs", MODE_PRIVATE)
val savedCount = sharedPreferences.getInt("textCount", 0)
textCount.text = savedCount.toString()
}

private fun sendUpdateBroadcast(count: Int) {
val intent = Intent("com.example.UPDATE_TEXT_COUNT")
intent.putExtra("textCount", count)
sendBroadcast(intent)
}

fun updateTextCount(newValue: Int) {
// Update the TextView
textCount.text = newValue.toString()
// Save the new value
saveTextCount(newValue)
// Send broadcast
sendUpdateBroadcast(newValue)
}
}
Ниже приведен код моего класса адаптера с именем PractiseAdapter.kt

Код: Выделить всё

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.cardview.widget.CardView
import androidx.recyclerview.widget.RecyclerView

class PractiseAdapter(
private val items:List,
private val textCount:TextView
):RecyclerView.Adapter
() {

private var count=0

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CardViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.cardview_item, parent, false)
return CardViewHolder(view)
}

override fun onBindViewHolder(holder: CardViewHolder, position: Int) {
val item = items[position]
holder.textView.text = item

// Optionally set up click listeners or other interactions
holder.cardView.setOnClickListener {
// Increment the count
val currentCount = textCount.text.toString().toIntOrNull() ?: 0
val newCount = currentCount + 1
(textCount.context as MainActivity).updateTextCount(newCount)
}
}

override fun getItemCount(): Int = items.size

class CardViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val cardView: CardView = itemView.findViewById(R.id.cardView1)
val textView: TextView = itemView.findViewById(R.id.textName)
}

}
Во «Втором» действии у меня есть TextView с именем «textSecondCount», представление recyclerview с именем «recycler1» и кнопка с именем «buttonSecond». textSecond count отображает значение textCount из MainActivity.kt. Существует класс адаптера с именем SecondAdapter.kt. когда я нажимаю на присутствующее в нем изображение карты, появляется диалоговое окно, подобное этому изображению пользовательского интерфейса, как вы можете видеть в диалоговом окне, когда я нажимаю кнопку «ДА», происходит вычитание textSecondCount и значение по умолчанию 10 Textview, присутствующее в SecondAdapter. А затем textSecondCount обновляется новым значением newCount. Ниже приведен код моего второго действия

Код: Выделить всё

import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.SharedPreferences
import android.os.Build
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView

class Second:AppCompatActivity() {

private lateinit var textSecondCount:TextView
private lateinit var buttonSecond:Button
private lateinit var recycler1:RecyclerView

@RequiresApi(Build.VERSION_CODES.O)
@SuppressLint("MissingInflatedId")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.second)

textSecondCount = findViewById(R.id.textSecondCount)
buttonSecond = findViewById(R.id.buttonBack)
recycler1 = findViewById(R.id.recycler1)

// Register receiver
registerReceiver(updateReceiver, IntentFilter("com.example.UPDATE_TEXT_COUNT"),
RECEIVER_NOT_EXPORTED
)

// Load the saved text count
loadTextCount()

buttonSecond.setOnClickListener {
onBackPressed()
}

val items = listOf("A1")
val adapter = SecondAdapter(this,items,textSecondCount)
recycler1.layoutManager = LinearLayoutManager(this)
recycler1.adapter = adapter

}

override fun onDestroy() {
super.onDestroy()
// Unregister receiver
unregisterReceiver(updateReceiver)
}

private fun loadTextCount() {
val sharedPreferences: SharedPreferences = getSharedPreferences("MyPrefs", MODE_PRIVATE)
val savedCount = sharedPreferences.getInt("textCount", 0)
findViewById(R.id.textSecondCount).text = savedCount.toString()
}

fun sendUpdateBroadcast(newCount:Int){
val intent = Intent("com.example.UPDATE_TEXT_COUNT")
intent.putExtra("textCount", newCount)
sendBroadcast(intent)
}
private val updateReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
val newCount = intent?.getIntExtra("textCount", 0) ?: 0
findViewById(R.id.textSecondCount).text = newCount.toString()
}
}
}
Код класса адаптера:

Код: Выделить всё

import android.annotation.SuppressLint
import android.content.Context
import android.os.Build
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AlertDialog
import androidx.cardview.widget.CardView
import androidx.recyclerview.widget.RecyclerView

class SecondAdapter(
private val context: Context,
private val items: List,
private val textSecondCount: TextView
) : RecyclerView.Adapter() {

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CardViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.second_adapter, parent, false)
return CardViewHolder(view)
}

@RequiresApi(Build.VERSION_CODES.O)
override fun onBindViewHolder(holder: CardViewHolder, position: Int) {
val item = items[position]
holder.textViewAdapter.text = holder.textViewAdapter.text

// Log item value and TextView text
Log.d("charm", "Item: $item")
Log.d("charm", "TextView value: ${holder.textViewAdapter.text}")

holder.cardViewSecond.setOnClickListener {
// Get the texAdapterCount value for the clicked card
val textAdapter = holder.textViewAdapter.text.toString()
val texAdapterCount = textAdapter.toIntOrNull() ?: 0

// Log the value to check conversion
Log.d("SecondAdapter", "texAdapterCount: $texAdapterCount")

showDialog(texAdapterCount)
}
}

@RequiresApi(Build.VERSION_CODES.O)
@SuppressLint("SetTextI18n")
private fun showDialog(texAdapterCount: Int) {
// Debugging:  Log the value of texAdapterCount
Log.d("SecondAdapter", "texAdapterCount: $texAdapterCount")

val dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_layout, null)
val messageTextView = dialogView.findViewById(R.id.dialog_message)

// Log current textSecondCount value
val currentCount = textSecondCount.text.toString()
Log.d("SecondAdapter", "Current textSecondCount: $currentCount")

// Ensure there's a space between the message and the count
messageTextView.text = "Do you have apples $texAdapterCount?"

val dialogBuilder = AlertDialog.Builder(context)
.setView(dialogView)
.setCancelable(true)

val dialog = dialogBuilder.create()

dialogView.findViewById(R.id.dialog_button_positive).setOnClickListener {
try {
val currentCountInt = currentCount.toInt()
if (currentCountInt >= texAdapterCount) {
// Update textSecondCount and notify the change
val newCount = currentCountInt - texAdapterCount
textSecondCount.text = newCount.toString()

// Save updated count to SharedPreferences
val sharedPreferences = context.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
editor.putInt("textCount", newCount)
editor.apply()

// Notify the user
showToast("Card unlocked successfully")

// Send update broadcast
if (context is Second) {
(context as Second).sendUpdateBroadcast(newCount)
}
} else {
// Notify the user
showToast("Not enough points to unlock")
}

} catch (e: NumberFormatException) {
Log.e("SecondAdapter", "Error parsing count: $e")
showToast("Error processing the count")
}
dialog.dismiss()
}

dialogView.findViewById(R.id.dialog_button_negative).setOnClickListener {
// Handle negative button click
dialog.dismiss()
}

dialog.show()
}

private fun showToast(messsage: String) {
Toast.makeText(context, messsage, Toast.LENGTH_SHORT).show()
}

override fun getItemCount(): Int = items.size

class CardViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val cardViewSecond: CardView = itemView.findViewById(R.id.cardViewSecond)
val textViewAdapter: TextView = itemView.findViewById(R.id.texAdapterCount)
}
}
Итак, теперь, когда я нажимаю кнопку «ДА», присутствующую в Alertdialog, происходит вычитание, и я получаю новое значение для textSecondCount, и я хочу, чтобы значение моего textCount также обновлялось на то же значение.
Я пытался передать значение в MainActivity, чтобы изменения могли отразиться и там, но значение textCount не меняется при изменении значения text SecondCount.>

Подробнее здесь: https://stackoverflow.com/questions/787 ... alue-of-te
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Android»