Android with Kotlin - Sending data back to MainActivity - android

I have two activities. I want to receive a value from MainActivity, change the value from SecondActivity, and send it back to editText of MainActivity.
However, the editText of MainActivity does not change even if I move back from SecondActivity.
Could you tell me which part I misunderstood?
MainActivity.kt code
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.result.contract.ActivityResultContracts
import com.example.homework07.databinding.ActivityMainBinding
import com.google.android.material.snackbar.Snackbar
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val result = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
it.resultCode
val ret_num = it.data?.getIntExtra("result", 0) ?:0
Snackbar.make(binding.root, "result code: ${it.resultCode}, result number: ${ret_num}", Snackbar.LENGTH_SHORT).show()
}
binding.button.setOnClickListener {
val intent = Intent(this, SecondActivity::class.java)
intent.putExtra("num", Integer.parseInt(binding.editText.text.toString()))
result.launch(intent)
}
}
}
activity_main.xml code
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:ems="10"
android:hint="Enter number only"
android:inputType="number"
android:minHeight="48dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="START SECOND ACTIVITY"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/editText" />
</androidx.constraintlayout.widget.ConstraintLayout>
SecondActivity.kt code
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.lifecycle.ViewModelProvider
import com.example.homework07.databinding.ActivitySecondBinding
class SecondActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivitySecondBinding.inflate(layoutInflater)
setContentView(binding.root)
val viewModel = ViewModelProvider(this)[MyViewModel::class.java]
viewModel.myLiveData.observe(this) {
binding.textView.text = "$it"
}
var num2 = intent?.getIntExtra("num", 0) ?:0
binding.textView.text = "$num2"
binding.buttonInc.setOnClickListener {
num2 = viewModel.myLiveData.value ?:0
viewModel.myLiveData.value = Integer.parseInt(binding.textView.text.toString()) + 1
}
binding.buttonDec.setOnClickListener {
num2 = viewModel.myLiveData.value ?:0
viewModel.myLiveData.value = Integer.parseInt(binding.textView.text.toString()) - 1
}
setResult(0, Intent().putExtra("result", num2))
}
}
activity_second.xml code
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SecondActivity">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:layout_marginTop="32dp"
android:text="TextView"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/buttonInc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="INCREASE"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/textView"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/buttonDec"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="DECREASE"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/textView"
app:layout_constraintTop_toBottomOf="#+id/buttonInc" />
</androidx.constraintlayout.widget.ConstraintLayout>
MyViewModel.kt code
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class MyViewModel : ViewModel() {
val myLiveData : MutableLiveData<Int> = MutableLiveData()
}
Thank you.

You made a mistake:
setResult(0, Intent().putExtra("result", num2))
replace 0 (it cancel result) to Activity.RESULT_OK.

This line has a mistake (resultCode) parameter:
setResult(0, Intent().putExtra("result", num2))
It's better if you make a constant for resultCode or do something like this in your SecondActivity.kt.
setResult(200, Intent().putExtra("result", num2))
And in MainActivity.kt add this is "registerActivityForResult":
if(it.resultCode == 200){
//Rest of the code here
}
Or you can also follow Below answer

You should set the result before finishing the SecondActivity with:
intent.putExtra("result", num2)
setResult(Activity.RESULT_OK, intent)
finish()
The, after checking the result, retrieve the value in the FirstActivity:
val result = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
val ret_num = result.data?.getIntExtra("result", 0) ?:0
Snackbar.make(binding.root, "result code: ${it.resultCode}, result number: ${ret_num}", Snackbar.LENGTH_SHORT).show()
}
}

Related

How use View.OnClickListener with FirestoreRecyclerAdapter

I'm trying to create an application and considering my level it's not easy! I hope you could help me since I didn't succeed with the many links I found on the internet.
I can't add the onClick function of View.OnClickListener, each time the Intent function is not recognized. I tried to implement it in the UserViewHolder and FirestoreRecyclerAdapter class but it doesn't work.
Here is my current code:
---------- kotlin part ---------
package edu.stanford.rkpandey.emojistatus
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.*
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.firebase.ui.firestore.FirestoreRecyclerAdapter
import com.firebase.ui.firestore.FirestoreRecyclerOptions
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.ktx.auth
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
import kotlinx.android.synthetic.main.activity_main.*
data class User(
val displayName: String? = "",
val emojis: String? = ""
)
class UserViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
class MainActivity : AppCompatActivity() {
private val db = Firebase.firestore
private lateinit var auth: FirebaseAuth
// Query the users collection
private val query = db.collection("users")
val options = FirestoreRecyclerOptions.Builder<User>()
.setQuery(query, User::class.java)
.setLifecycleOwner(this).build()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
auth = Firebase.auth
val adapter = object: FirestoreRecyclerAdapter<User, UserViewHolder>(options) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserViewHolder {
val view = LayoutInflater.from(this#MainActivity).inflate(R.layout.item_pack, parent, false)
return UserViewHolder(view)
}
override fun onBindViewHolder(
holder: UserViewHolder,
position: Int,
model: User
) {
val tvName: TextView = holder.itemView.findViewById(R.id.title)
val tvEmojis: TextView = holder.itemView.findViewById(R.id.excerpt)
tvName.text = model.displayName
tvEmojis.text = model.emojis
}
}
rvUsers.adapter = adapter
rvUsers.layoutManager = LinearLayoutManager(this)
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.miLogout) {
Log.i("MainActivity", "Logout")
auth.signOut()
val logoutIntent = Intent(this, LoginActivity::class.java)
logoutIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
startActivity(logoutIntent)
}
return super.onOptionsItemSelected(item)
}
}
------- xml part -------
=> activity_main
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rvUsers"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
=> item_pack
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="100sp"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.cardview.widget.CardView
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="12sp"
android:layout_marginTop="12sp"
android:layout_marginEnd="12sp"
android:focusable="true"
android:clickable="true"
app:cardCornerRadius="10dp"
android:foreground="?android:attr/selectableItemBackground">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
android:background="#color/colorPack">
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5sp"
style="#style/NoteTitleFont"
android:textColor="#color/colorTitle"
tools:text="Note 1" />
<TextView
android:id="#+id/excerpt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="12sp"
android:layout_below="#id/title"
android:maxLines="1"
android:ellipsize="end"
android:textStyle="italic"
android:textColor="#color/colorDescribe"
tools:text="test text va se trouver ici, ça va contenir le début de la description du package." />
</RelativeLayout>
</androidx.cardview.widget.CardView>
</RelativeLayout>
This code gives this result :
I would like that when I click on one of the carviews it can go to the activity_pack_detail.
Do you know how to do Intent to PackDetailActivity?
I get this error no matter what I do =>
You're getting that error because you are calling Intent's class constructor with a wrong argument. The first argument should be a Context and not a View. The keyword this is referring in your code to a View and not to a context, hence the error.
To solve this, you have to pass a Context object like this:
val i = Intent(view.getContext(), PackDetailActivity::class.java)
And your error will go away.

I want change profile using image capture on navigation drawer ? its possible?

Navigation drawer
I wrote this code but problem is crash application.
This id my nav_header file xml code,i am using circleimageview and imagebutton.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="16dp"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:background="#color/white">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/Profile"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:src="#drawable/ic_baseline_person_24"
app:civ_border_color="#color/black"
app:civ_border_width="2dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageButton
android:id="#+id/change_Profile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/background_center"
app:layout_constraintBottom_toBottomOf="#+id/Profile"
app:layout_constraintEnd_toEndOf="#+id/Profile"
app:srcCompat="#drawable/ic_baseline_add_circle_24" />
<TextView
android:id="#+id/User_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="72dp"
android:paddingTop="8dp"
android:text="Robin Hud"
android:textColor="#color/black"
android:textSize="20dp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="110dp"
android:text="sufiyan123#gmail.com"
android:textSize="16dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="135dp"
android:background="#color/underline"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
----------
This is kotlin file code for navigation drawer
package com.example.pgf.view.home
import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.MediaStore
import android.view.MenuItem
import android.widget.ImageButton
import android.widget.Toast
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.drawerlayout.widget.DrawerLayout
import androidx.fragment.app.Fragment
import com.example.pgf.R
import com.example.pgf.model.PGListModel
import com.example.pgf.view.authentication.Login
import com.example.pgf.view.home.fragments.*
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.navigation.NavigationView
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
import de.hdodenhof.circleimageview.CircleImageView
class MainActivity : AppCompatActivity() {
private lateinit var toggle: ActionBarDrawerToggle
private lateinit var drawerLayout: DrawerLayout
var email:String? = null
var profile: CircleImageView? = null
var reqcode = 345
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//Profile change
profile = findViewById(R.id.Profile)
var btnChange = findViewById<ImageButton>(R.id.change_Profile)
btnChange.setOnClickListener {
var captureImage = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(captureImage,reqcode)
}
//get user Email
val user = FirebaseAuth.getInstance().currentUser
email = user?.email
Toast.makeText(applicationContext,email,Toast.LENGTH_SHORT).show()
drawerLayout = findViewById(R.id.drawer)
val navView: NavigationView = findViewById(R.id.navView)
toggle = ActionBarDrawerToggle(this,drawerLayout,R.string.open,R.string.close)
drawerLayout.addDrawerListener(toggle)
toggle.syncState()
supportActionBar?.setDisplayHomeAsUpEnabled(true)
replaceFragment(HomeFragment(),"Home")
navView.setNavigationItemSelectedListener {
it.isChecked = true
when(it.itemId){
R.id.nav_home -> replaceFragment(HomeFragment(),it.title.toString())
R.id.nav_star -> replaceFragment(StarFragment(),it.title.toString())
R.id.nav_help -> replaceFragment(HelpFragment(),it.title.toString())
R.id.nav_setting -> replaceFragment(SettingFragment(),it.title.toString())
R.id.nav_profile -> replaceFragment(ProfileFragment(),it.title.toString())
R.id.nav_logout -> logout()
R.id.nav_share -> Toast.makeText(applicationContext,"Clicked Share",Toast.LENGTH_SHORT).show()
}
true
}
}
private fun replaceFragment(fragment: Fragment, title: String){
val fragmentStateManagerControl = supportFragmentManager
val fragmentTransaction = fragmentStateManagerControl.beginTransaction()
fragmentTransaction.replace(R.id.framelayout,fragment)
fragmentTransaction.commit()
drawerLayout.closeDrawers()
setTitle(title)
}
fun logout(){
Firebase.auth.signOut()
startActivity(
Intent(this,Login::class.java)
)
this.finish()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (toggle.onOptionsItemSelected(item)){
return true
}
return super.onOptionsItemSelected(item)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if(resultCode== Activity.RESULT_OK && requestCode==reqcode && data!=null)
{
profile!!.setImageBitmap(data.extras?.get("data") as Bitmap)
}
else
{
Toast.makeText(applicationContext,"Something Went Wrong!!",Toast.LENGTH_LONG).show()
}
}
}
This is my all code,so I want to change profile picture using camera capture on navigation drawer.
so what I do for this?
Logcat
enter image description here

getLocationOnScreen always returns 0 on widget position

I am trying to find the position of widgets but somehow it always returns 0. I have followed most suggestions but all of them still returns 0. I finally ended up with this, but still it returns a 0. I have read somewhere that the reason it returns a 0 is because I am calling for the position before onCreate() has finished parsing the layout specified in the accompanying .xml file.
Where then should I put the call to the positions then?
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fuelCalculationConstraintLayout"
tools:context=".FuelCalculation">
<ImageView
android:id="#+id/imageViewIconHome"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/icon_home" />
<TextView
android:id="#+id/textViewSettingValues"
android:text="Settings:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="#id/imageViewIconHome"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:height="30dp"
android:width="100dp"/>
<TextView
android:id="#+id/textViewScratchPad"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Scratch Pad"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
package com.example.fuelcalculation3
import android.content.Context
import android.content.Intent
import android.graphics.Point
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class FuelCalculation : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_fuel_calculation)
val updateTextViewSettingValues = findViewById<TextView>(R.id.textViewSettingValues)
val updateTextViewScratchPad = findViewById<TextView>(R.id.textViewScratchPad)
val imageIconHomeClick = findViewById<ImageView>(R.id.imageViewIconHome)
imageIconHomeClick.setOnClickListener(){
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
}
fun View.getLocationOnScreen(): Point {
val location = IntArray(2)
this.getLocationOnScreen(location)
return Point(location[0], location[1])
}
val location = updateTextViewSettingValues.getLocationOnScreen()
val absX = location.x
val absY = location.y
val getTextViewSettingsRootView = updateTextViewSettingValues.rootView
val getTextViewSettingsValueWidth = updateTextViewSettingValues.width
val getTextViewSettingsValueTop = updateTextViewSettingValues.top
val getTextViewSettingsValueLeft = updateTextViewSettingValues.left
val getTextViewSettingsValueRight = updateTextViewSettingValues.right
val getTextViewSettingsValueMeasuredWidth = updateTextViewSettingValues.measuredWidth
val getTextViewSettingsValueA = updateTextViewSettingValues.measuredWidth
updateTextViewScratchPad.text = "Top=$getTextViewSettingsValueTop" // returns 0
updateTextViewScratchPad.text = "$absX" // returns 0
}
}
See Why getLocationOnScreen(location) always returns 0?. You are to use postDelayed or getViewTreeObserver to get view position after an activity has rendered. Maybe you should use requestLayout.

How can I do a setOnClickListener to a fragment that is not in my Activity?

I have 3 fragments here I show them, they have a TextView with the id omitir_swipe, and I need to use it in the activity where I show those 3 fragments, how would I achieve it?:
3 fragments xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#color/colorWhite"
>
<ImageView
android:id="#+id/image_swipe"
android:layout_width="200dp"
android:layout_height="200dp"
android:src="#drawable/books_swipe"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.246"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.329"
/>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="116dp"
android:text="Amantium irae amoris integratio est."
android:textAlignment="center"
android:textColor="#color/colorBlack"
android:textSize="16dp"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="#+id/image_swipe"
app:layout_constraintEnd_toEndOf="#+id/image_swipe"
app:layout_constraintHorizontal_bias="0.465"
app:layout_constraintStart_toStartOf="#+id/image_swipe" />
<TextView
android:id="#+id/omitir_swipe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Omitir"
android:textSize="16sp"
android:textStyle="bold"
android:layout_marginRight="30dp"
android:textColor="#color/colorBlack"
app:layout_constraintHorizontal_bias="1"
app:layout_constraintBottom_toBottomOf="#+id/textView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/textView"
app:layout_constraintTop_toTopOf="#+id/textView" />
</androidx.constraintlayout.widget.ConstraintLayout>
The 3 are the same so I only upload 1, they have the same id, to only use 1, I don't know if this is good, could you tell me whether to change it or not
3 Fragments .kt kotlin:
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.yr.iolite.R
class SwipeFragement1 : Fragment()
{
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_splash_screen_1, container, false)
}
}
in the 3 only change this number fragment_splash_screen_change this number
The activity where I show the 3 fragments xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Splash.SplashActivity">
<ImageView
android:id="#+id/bg_snow_splash"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:src="#drawable/bg_snow"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
<ImageView
android:id="#+id/logo_splash"
android:layout_width="320dp"
android:layout_height="200dp"
android:layout_marginTop="20dp"
android:src="#drawable/logo"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0"
/>
<com.airbnb.lottie.LottieAnimationView
android:id="#+id/penguin_splash"
android:layout_width="250dp"
android:layout_height="300dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.391"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/logo_splash"
app:layout_constraintVertical_bias="0"
app:lottie_autoPlay="true"
app:lottie_loop="true"
app:lottie_rawRes="#raw/party_penguin"
/>
<com.cuberto.liquid_swipe.LiquidPager
android:id="#+id/swipe_screen"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
The .kt from the previous activity:
import android.content.Intent
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.provider.AlarmClock.EXTRA_MESSAGE
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.viewpager.widget.ViewPager
import com.airbnb.lottie.LottieAnimationView
import com.yr.iolite.MainActivity
import com.yr.iolite.R
import com.yr.iolite.WriteProblem.MinOrMax
import kotlinx.android.synthetic.main.activity_splash.*
import kotlinx.android.synthetic.main.fragment_splash_screen_1.*
class SplashActivity : AppCompatActivity()
{
var bg: ImageView? = null
var logo: ImageView? = null
var penguin: LottieAnimationView? = null
var anim: Animation? = null
private var pagerAdapter : ScreenSliderPagerAdapter? = null
private val SPLASH_TIME_OUT : Int = 5500
private var sharedPref : SharedPreferences ? = null
private var omitir_swipe : TextView? = null
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)
bg = findViewById(R.id.bg_snow_splash)
logo = findViewById(R.id.logo_splash)
penguin = findViewById(R.id.penguin_splash)
omitir_swipe = findViewById(R.id.omiti_swipe)
val viewPager : ViewPager = findViewById(R.id.swipe_screen)
pagerAdapter = ScreenSliderPagerAdapter(supportFragmentManager)
viewPager.adapter = pagerAdapter
anim = AnimationUtils.loadAnimation(this, R.anim.swipe_screen_anim)
viewPager.startAnimation(anim)
bg_snow_splash.animate().apply {
duration = 1000
startDelay = 4000
translationY(-1600f)
}
logo_splash.animate().apply {
duration = 1000
startDelay = 4000
translationY(-1400f)
}
penguin_splash.animate().apply {
duration = 1000
startDelay = 4000
translationY(1400f)
}
Handler(Looper.getMainLooper()).postDelayed({
var sharedPref= getSharedPreferences("SharedPref", MODE_PRIVATE)
var isFirstTime : Boolean = sharedPref.getBoolean("firstTime", true)
if(isFirstTime)
{
var editor : SharedPreferences.Editor = sharedPref.edit()
editor.putBoolean("firstTime", false)
editor.commit()
}
else
{
val intent = Intent(this, MinOrMax::class.java).apply {
putExtra(EXTRA_MESSAGE, "Intento con exito")
}
startActivity(intent)
finish()
}
}, 5000)
/*findViewById<TextView>(R.id.omitir_swipe).setOnClickListener{
val intent = Intent(this, MainActivity::class.java).apply {
putExtra(EXTRA_MESSAGE, "xd")
}
startActivity(intent)
finish()
}*/
}
private class ScreenSliderPagerAdapter (fm : FragmentManager) : FragmentStatePagerAdapter(fm)
{
val NUM_TABS = 3
override fun getItem(position: Int): Fragment
{
return when (position)
{
0 -> SwipeFragement1()
1 -> SwipeFragement2()
else -> SwipeFragement3()
}
}
override fun getCount(): Int = NUM_TABS
}
}
I don't have any errors but when I uncomment the setOnClickListener it doesn't work it gives me a null pointer exception error, and that is because the id of the omit_swipe is not in the activity xml as you can see above instead it is in the fragments.
You can start a new activity and finish the current from the fragment.
class SwipeFragement1 : Fragment(){
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_splash_screen_1, container, false)
view.findViewById<TextView>(R.id.omitir_swipe).setOnClickListener{
val intent = Intent(activity, MainActivity::class.java).apply {
putExtra(EXTRA_MESSAGE, "xd")
}
activity.startActivity(intent)
activity.finish()
}
return view
}
}

Android Kotlin cannot change a text string within a function

I have some really simple Kotlin code for changing a text string within a function generated from a button press, but it does not work. I have a single button and two text strings, one the button press the first text string changes but the text string within the function does not change.
I am sure the problem is with the function call and not passing the right information about the activity, but just cannot work out what is wrong.
MainActivty.kt
package com.example.sandpit9
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.activity_main.view.*
import org.w3c.dom.Text
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
imageButton1.setOnClickListener {v: View -> toast(v) }
imageButton1.setOnClickListener {
imageButton1.setImageResource(R.drawable.greenbutton)
textView1.text = "1234"
}
}
public fun toast(v: View) {
v.textView2.text = "1234"
}
}
MainActivty.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView1"
android:layout_marginTop="8dp"
app:layout_constraintTop_toBottomOf="#+id/imageButton1"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
app:layout_constraintStart_toStartOf="parent"
android:layout_marginLeft="8dp"
android:layout_marginStart="8dp"
android:textSize="34sp"/>
<TextView
android:text="textvar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView2"
android:textSize="34sp"
android:layout_marginTop="108dp"
app:layout_constraintTop_toBottomOf="#+id/imageButton1"
android:layout_marginEnd="8dp"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
app:layout_constraintStart_toStartOf="parent"
android:layout_marginLeft="8dp"
app:layout_constraintHorizontal_bias="0.535"/>
<ImageButton
android:layout_width="174dp"
android:layout_height="154dp"
app:srcCompat="#drawable/download"
android:id="#+id/imageButton1"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
app:layout_constraintStart_toStartOf="parent"
android:layout_marginLeft="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.542"
app:layout_constraintVertical_bias="0.187"/>
</android.support.constraint.ConstraintLayout>
You're overwriting the click listener. The OnClickListener is a single property - not a list.
imageButton1.setOnClickListener {v: View ->
toast(v)
imageButton1.setImageResource(R.drawable.greenbutton)
textView1.text = "1234"
}
imageButton1.setOnClickListener {v: View -> toast(v) }
imageButton1.setOnClickListener {
imageButton1.setImageResource(R.drawable.greenbutton)
textView1.text = "1234"
}
Problem: ImageButton have only one OnClickListener to listen the event when there is a click event on it own. You can set the listener by using setOnClickListener. Because in your code, you use setOnClickListener two times, so the second one will override the first one.
Solution: Change your code to
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
imageButton1.setOnClickListener {
imageButton1.setImageResource(R.drawable.greenbutton)
textView1.text = "1234"
textView2.text = "1234"
}
}
}
Many thanks, how simple is the solution many thanks for all the help, the setOnClickListener is setup only once to trigger the function. This is the finial code that works
package com.example.sandpit9
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.activity_main.view.*
import org.w3c.dom.Text
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
imageButton1.setOnClickListener{v: View -> toast(v)}
}
private fun toast(v: View) {
imageButton1.setImageResource(R.drawable.greenbutton)
textView1.text = "1234"
textView2.text = "1234"
}
}
remove this import
import kotlinx.android.synthetic.main.activity_main.view.*
Hope this will work

Categories

Resources