How to change the text on the second activity on button clicked from first activity? [KOTLIN] - android

I have to implement OTP validation on my application, I just want to get the mobile number from the previous activity and set it to the textview on the next activity once I clicked the Next Button intent from Activity 1 to Activity 2.
Here is how it looks like in view:
I would like to put the mobile number below the please enter the otp that has sent to..
First try: I called the ObjectSingleton.mobileNum since it carries the mobile # then I used mobileNum.setText(ObjectSingleton.mobileNum) but it ddint work.
My codes in 1st Activity where intent is happening to go to the next Activity;
class MobileNumberActivity : AppCompatActivity(), OtpInterface.MobileNumberViews {
lateinit var presenterMobileNumber:MobileNumberPresenter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_mobile_number)
presenterMobileNumber = MobileNumberPresenter()
presenterMobileNumber.mobileViews = this
close_icon2.setOnClickListener {
finish()
}
nxtBtn.setOnClickListener {
if (inputText.text.isNullOrEmpty()) {
inputText.error = "Please enter valid mobile number."
} else if (inputText.text.toString().length != 10) {
inputText.error = "Please enter valid mobile number."
} else{
val mobile = inputText.text.toString()
presenterMobileNumber.otpMobile(mobile)
}
}
}
override fun ifFailed(msg: String) {
errorMsg.setText(msg)
}
override fun ifSuccess(res: OtpData) {
errorMsg.setText("Sent!")
var intent = Intent(this, OtpValidationActivity::class.java)
startActivity(intent)
}
Here are the codes of the 2nd Acitivy where I want to change the text of mobile number display
class OtpValidationActivity : AppCompatActivity(), OtpValidateInterface.OtpValidateViews {
lateinit var otpPresenter: OtpPresenter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_otp_verification)
otpPresenter = OtpPresenter()
otpPresenter.otpValidationViews = this
verifyOtpBtn.setOnClickListener {
if (otp_input.text.isNullOrEmpty()) {
otp_input.error = "Please enter OTP."
} else{
val otpNumber = otp_input.text.toString()
otpPresenter.otpValidate(ObjectSingleton.mobileNum,otpNumber)
}
}
}
override fun validateFailed(res: String) {
resend.setText("Failed")
}
override fun validateSuccess(msg: OtpValidationData) {
resend.setText("Success")
}
For your REFERENCE here's the XML file of the said PICTURE above where should I put the Mobile number.
<?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"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/rectangle"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<LinearLayout
android:id="#+id/linearLayout6"
android:layout_width="372dp"
android:layout_height="wrap_content"
android:background="#drawable/otpbg"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.487"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.041">
<LinearLayout
android:id="#+id/linearLayout5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/_30sdp"
android:text="OTP VERIFICATION"
android:textColor="#color/reply_black_800"
android:textSize="#dimen/_22sdp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</TextView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Please enter the OTP that has sent to">
</TextView>
<TextView
android:id="#+id/mobileNum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/_22sdp"
android:layout_marginBottom="#dimen/_30sdp"
android:text="#string/_63"
android:textColor="#color/colorPrimary"
android:textSize="#dimen/_19sdp"
android:textStyle="bold">
</TextView>
</LinearLayout>
<com.mukesh.OtpView
android:id="#+id/otp_input"
android:layout_width="267dp"
android:layout_height="48dp"
android:layout_gravity="center"
android:layout_marginLeft="#dimen/_10sdp"
android:layout_marginRight="#dimen/_10sdp"
android:inputType="number"
android:textAppearance="?attr/textAppearanceHeadline5"
android:textColor="#android:color/black"
app:OtpItemCount="6"
app:OtpItemWidth="#dimen/_30sdp"
app:OtpLineColor="#color/reply_black_800"
app:OtpViewType="line" />
<TextView
android:id="#+id/resend"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/_19sdp"
android:gravity="center"
android:textSize="#dimen/_14sdp"
android:text="#string/didn_t_recieve_the_code_resend_code"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/otp_view"
app:layout_constraintVertical_bias="0.039"
android:paddingBottom="#dimen/_30sdp"/>
</LinearLayout>
<androidx.appcompat.widget.AppCompatButton
android:id="#+id/verifyOtpBtn"
android:layout_width="378dp"
android:layout_height="42dp"
android:background="#drawable/radius_btn"
android:backgroundTint="#color/colorPrimary"
android:text="Next"
android:textAllCaps="false"
android:textColor="#color/white"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.484"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/linearLayout6"
app:layout_constraintVertical_bias="0.117" />
</androidx.constraintlayout.widget.ConstraintLayout>
I am new to Kotlin/Android Develepment I hope someone help me with this.
#JUniorDEV
UPDATE: Imma share to you my MobileNumberPresenter codes:
var mobileViews:OtpInterface.MobileNumberViews? = null
override fun otpMobile(mobile: String) {
Fuel.post("https://api.staging.riderko.com/riderko_be/public/api/riderSendRegisterOtp", listOf(
"mobile" to mobile
)).timeout(5000)
.header("Accept", "application/json")
.responseObject<OtpResponse>{request, response, result ->
when (result) {
is Result.Failure -> {
mobileViews?.ifFailed(result.error.response.statusCode.toString())
}
is Result.Success -> {
val (bytes, error) = result
if (bytes != null) {
val status = bytes.success
if (status){
mobileViews?.ifSuccess(bytes.data)
}else{
mobileViews?.ifFailed(bytes.message)
}
}
}
}
}
}

in OtpInterface.MobileNumberViews
add second parameter as string to ifSuccess
in MobileNumberPresenter
change mobileViews?.ifSuccess(bytes.data) to mobileViews?.ifSuccess(bytes.data, mobile)
and you ifSuccess method will be changed to
override fun ifSuccess(res: OtpData, mobileNum: String) {
errorMsg.setText("Sent!")
var intent = Intent(this, OtpValidationActivity::class.java)
intent.putExtra("MOBILE_NUMBER",mobileNum)
startActivity(intent)
}
And in OtpValidationActivity
val mobileNum = arguments?.getString("MOBILE_NUMBER")

Update the code of 1st activity to
override fun ifSuccess(res: OtpData) {
errorMsg.setText("Sent!")
var intent = Intent(this, OtpValidationActivity::class.java)
startActivity(intent)
intent.putExtra("MobileNum",mobile)
}
Now in the second activity after setContentView(R.layout.activity_otp_verification)
add this line:
val MobNo = intent.getExtra("MobileNum")
mobileNum.text = MobNo
Hope this will work

Here in the MobileNumberActivity inside the ifSuccess() before you do startActivity(intent) do intent.putExtra("IDENTIFER",mobileNum)
Now in the 2nd activity simply do val mobNO = intent.getStringExtra("IDENTIFER")
and now assign the mobNo to the desired textView.
This helps pass data between activities.

I was able to solve this simply by calling ObjectSingleton.mobNum assigned to a variable and displayed it into view I just learnt that once objectsingleton has been assigned to, the value will be carried over to any part of your app, this value will be removed automatically when you close your app.

Related

Why does SetOnClickListener not always work?

I found out that sometimes setOnClickListener doesn't work when I click the view. When I run the application and click the view, it has no response, there is no error message it just doesn't work.
In the other part of the project setOnClickListener works well and I can't find any difference. I have no idea why it is not working even though the code is same.
Here is my activity file.
class SplashActivity : AppCompatActivity() {
// 애니메이션을 처리하기 위한 runnable 객체
private val mRunnable : Runnable = Runnable {
if (!isFinishing) { // 끝나지 않았을 때
// 슬라이드업 애니메이션 실행
slideUp(illo_logo, 500)
fadeIn(illo_copy, 500)
slideUp(illo_copy, 500)
fadeIn(btn_login, 500)
slideUp(btn_login, 500)
fadeIn(btn_sign, 500)
slideUp(btn_sign, 500)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)
// 핸들러 이용해 0.5초 딜레이 후 mRunnable 실행
Handler().postDelayed(mRunnable, 500)
// 로그인 버튼
btn_login.setOnClickListener {
Toast.makeText(this#SplashActivity, "로그인 버튼 클릭", Toast.LENGTH_SHORT).show()
val intent = Intent(this#SplashActivity, LoginActivity::class.java)
startActivity(intent)
finish()
}
// 가입 버튼
btn_sign.setOnClickListener {
Toast.makeText(this#SplashActivity, "가입 버튼 클릭", Toast.LENGTH_SHORT).show()
val intent = Intent(this#SplashActivity, SignActivity0::class.java)
startActivity(intent)
finish()
}
}
// 위로 올리기
fun slideUp(view : View, time : Int) {
val animation = TranslateAnimation(0f, 0f, 0f, -300f ) // 애니메이션 인스턴스화
animation.duration = time.toLong() // 애니메이션 지속시간 설정
animation.fillAfter = true // 애니메이션 종료 후 상태 유지
view.startAnimation(animation) // 애니메이션 실행
}
// 페이드 인
fun fadeIn(view: View, time: Int) {
val anim = AnimationUtils.loadAnimation(this#SplashActivity, R.anim.fade_in) // 애니메이션 로드
anim.duration = time.toLong() // 애니메이션 지속시간
anim.fillAfter = true // 애니메이션 종료 후 상태 유지
view.startAnimation(anim) // 애니메이션 실행
}
}
Here is my 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"
android:background="#color/illo_base_color"
tools:context=".SplashActivity">
<ImageView
android:id="#+id/illo_logo"
android:layout_width="140dp"
android:layout_height="140dp"
android:layout_marginBottom="250dp"
android:src="#drawable/app_icon_default"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="#+id/illo_copy"
android:layout_width="141dp"
android:layout_height="26dp"
android:layout_marginTop="4dp"
android:layout_marginBottom="206dp"
android:fontFamily="#font/tmoneyroundwind_extrabold"
android:letterSpacing="0"
android:text="우리는 illo 모임"
android:textColor="#color/illo_light_purple"
android:textSize="20sp"
android:textStyle="normal"
android:visibility="invisible"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="#+id/illo_logo"
app:layout_constraintStart_toStartOf="#+id/illo_logo"
app:layout_constraintTop_toBottomOf="#+id/illo_logo"
app:layout_constraintVertical_bias="0.0" />
<RelativeLayout
android:id="#+id/btn_login"
android:layout_width="312dp"
android:layout_height="48dp"
android:layout_marginStart="24dp"
android:layout_marginTop="150dp"
android:layout_marginEnd="24dp"
android:background="#drawable/button_long"
android:visibility="invisible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/illo_copy">
<TextView
style="#style/IlloKrTitle1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="로그인하기"
android:textColor="#color/illo_white100"
android:textSize="16dp" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/btn_sign"
android:layout_width="312dp"
android:layout_height="48dp"
android:layout_marginStart="24dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="24dp"
android:background="#drawable/button_long"
android:visibility="invisible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/btn_login">
<TextView
style="#style/IlloKrTitle1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="가입하기"
android:textColor="#color/illo_white100"
android:textSize="16dp" />
</RelativeLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Add android:clickable = "true" and android:focusable = "true" on your widgets like:
<RelativeLayout
android:id="#+id/btn_login"
android:layout_width="312dp"
android:layout_height="48dp"
android:layout_marginStart="24dp"
android:layout_marginTop="150dp"
android:layout_marginEnd="24dp"
android:clickable="true"
android:focusable="true"
android:background="#drawable/button_long"
android:visibility="invisible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/illo_copy">
Extra: add this property android:foreground="?attr/selectableItemBackground" That code add selectable animation on RelativeLayout but work better if you added on android:background property. Work with any Widget try and play nice!! ;)
Did you forget to connect those variables? If you have added the whole activity's code than I don't think that doesn't return any error, it must return errors. Did you check logcat?
val btn_login = findViewById<Button>(R.id.btn_login)
If I am missing something than try by making btn_login clickable. Cause your btn_login isn't actually a button. It's a relativeLayout. And for some views default clicking expression is false by default that's why you must enable them.
android:clickable = "true"
I don't remember if it's the accurate one since I am not using Android Studio right now.
I guess you are using Kotlin Synthetic.
If you are using it, try to look at the imported files.
If you copied the same codes that have views in Kotlin Synthetic, it's also copied the same imported files.
Just delete the imported files and change them to the right ones.
Instead of:
import kotlinx.android.synthetic.main."Your layout name with same codes".*
Change it to:
import kotlinx.android.synthetic.main.activity_splash.*
It's better to discard Kotlin Synthetic and move on to ViewBinding

Align_parent programmatically reset

I have a problem with reset align_parent. The idea is that we have an object in the window and we can control it with buttons, but I have a problem with the fact that if I press setTop, it will reach the indicated position, but then when I press setBottom, the button is in place. I have the impression that the variable reset is not working properly but I don't understand why. Maybe you know if he is typing removeRule incorrectly or is there any other way to set the align_parent and center_horizontal values to false?
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_margins_train)
val testbox = findViewById<TextView>(R.id.testbox)
val setTop = findViewById<TextView>(R.id.setTop)
val setBottom = findViewById<TextView>(R.id.setBottom)
val parameters = RelativeLayout.LayoutParams(heightBox.toInt(),widthBox.toInt())
val reset = RelativeLayout.LayoutParams(heightBox.toInt(),widthBox.toInt())
.apply { removeRule(RelativeLayout.ALIGN_PARENT_END) }.apply { removeRule(RelativeLayout.ALIGN_PARENT_TOP) }
.apply { removeRule(RelativeLayout.ALIGN_PARENT_BOTTOM) }.apply { removeRule(RelativeLayout.ALIGN_PARENT_START) }
.apply { removeRule(RelativeLayout.CENTER_HORIZONTAL) }.apply { removeRule(RelativeLayout.CENTER_VERTICAL) }
setTop.setOnClickListener {
testbox.layoutParams = reset
testbox.layoutParams = parameters.apply { addRule(RelativeLayout.CENTER_HORIZONTAL) }.apply { addRule(RelativeLayout.ALIGN_PARENT_TOP) }
}
setBottom.setOnClickListener {
testbox.layoutParams = reset
testbox.layoutParams = parameters.apply { addRule(RelativeLayout.CENTER_HORIZONTAL) }.apply { addRule(RelativeLayout.ALIGN_PARENT_BOTTOM) } }
}
XML code
<RelativeLayout
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=".MarginsTrain">
<TextView
android:id="#+id/setTop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#id/testing"
android:layout_centerHorizontal="true"
android:layout_marginBottom="1dp"
android:background="#drawable/customborder_box"
android:paddingHorizontal="2dp"
android:paddingBottom="3dp"
android:textSize="14sp"/>
<TextView
android:id="#+id/setBottom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/testing"
android:layout_centerHorizontal="true"
android:layout_marginTop="1dp"
android:background="#drawable/customborder_box"
android:paddingHorizontal="2dp"
android:paddingTop="3dp"
android:textSize="14sp"/>
<RelativeLayout
android:id="#+id/testing"
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_centerInParent="true"
android:background="#color/teal_200">
<TextView
android:id="#+id/testbox"
android:layout_width="#dimen/testboxWidth"
android:layout_height="#dimen/testboxHeight"
android:background="#color/purple_500"
android:gravity="center"
android:text="#string/RelativeLayoutTestTextBox"
android:textColor="#color/white" />
</RelativeLayout>
</RelativeLayout>
The code
testbox.layoutParams = reset
has no effect since it is immediately followed by
testbox.layoutParams = parameters.apply { addRule(RelativeLayout.CENTER_HORIZONTAL) }.apply { addRule(RelativeLayout.ALIGN_PARENT_BOTTOM) } }
and is therefore overridden before a layout can occur. Maybe the following statement will help correct the problem:
testbox.layoutParams = reset.apply {
addRule(RelativeLayout.CENTER_HORIZONTAL)
addRule(RelativeLayout.ALIGN_PARENT_BOTTOM) } }
I would take a closer look at this area. I am also curious why there are so many chained .apply{} when one would do.

why i can't put view binding inside onClick listener?

i already define this :
class ProfileFragment : Fragment(), View.OnClickListener {}
and the onclick :
override fun onClick(v: View?) {
when (v!!.id) {
binding.tvNavSetting -> {
avoidDoubleClicks(binding.tvNavSetting)
val intent = Intent(requireContext(), SettingsActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
}
}
}
this is my Drawer & inside Profile Fragment.xml :
<com.google.android.material.navigation.NavigationView
app:elevation="10dp"
android:id="#+id/nav_view"
android:paddingBottom="100dp"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="end"
android:background="#color/white"
android:fitsSystemWindows="false">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.appcompat.widget.SearchView
android:layout_width="match_parent"
android:layout_height="40dp"
android:id="#+id/seach_view"
android:background="#drawable/bg_search"
android:layout_marginHorizontal="10dp"
android:layout_marginVertical="10dp"/>
// this is what i try to call:////
<TextView
android:id="#+id/tv_nav_setting"
android:text="awdadw"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/black" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginStart="20dp"
android:layout_marginEnd="40dp"
android:background="#drawable/drawer_bg" />
</LinearLayout>
<Button
android:id="#+id/btn_keluar_profile"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Keluar"
android:layout_margin="10dp"
android:textColor="#color/white"
android:background="#drawable/bg_btn_login"
android:layout_gravity="bottom"/>
</com.google.android.material.navigation.NavigationView>
i have Text View inside the Drawer Navigation inside Fragment.. i want handle click in that drawer navigation, but the text view can't call by viewBinding.. please have a look the error picture below..
when(v!!.id) means you want to use view with particular id (works like old Java switch case or just if(view.id == id), so binding.tvNavSetting -> ... should be binding.tvNavSetting.id -> .... currently you are comparing views id with whole view-object itself
sorry , i forgot to add this :
override fun onClick(v: View?) {
when (v!!.id) {
R.id.tv_nav_setting -> { <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
avoidDoubleClicks(binding.tvNavSetting)
val intent = Intent(requireContext(), SettingsActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
}
}
}
/*adding this line solve the problem*/
private fun setDrawer() {
binding.drawerLayout.setScrimColor(Color.TRANSPARENT)
binding.tvNavSetting.setOnClickListener(this) <<<-------
}
Instead of using view ids in when(v!!.id), we can use the comparison of views.
i.e Bind Listenser first
binding.bt1.setOnClickListener(this)
binding.bt2.setOnClickListener(this)
binding.bt3.setOnClickListener(this)
binding.bt4.setOnClickListener(this)
then
override fun onClick(view: View?) {
binding.apply {
when(view) {
bt1 -> {
println("bt1")
}
bt2 -> {
println("bt2")
}
bt3 -> {
println("bt3")
}
bt4 -> {
println("bt4")
}
}
}
}
Works perfectly since binding.bt1 gives View only.

Error when executing the application in android with setOnClickListener Kotlin

I tried to create a global variable and then make a R.id.omitir_swipe and it doesn't work either, it doesn't give me errors in the compilation but when executing on my cell phone or in the emulator the app stops working I attach the image:
Maybe it is not the correct function that it should be in, if so tell me, or if there is a better way to do that setOnclickListener, also mention that omit_swipe is not a variable, but rather it is an id of a textView.
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)
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, MainActivity::class.java).apply {
putExtra(EXTRA_MESSAGE, "Intento con exito")
}
startActivity(intent)
finish()
}
}, 5000)
omitir_swipe.setOnClickListener{
val intent = Intent(this, MainActivity::class.java).apply {
putExtra(EXTRA_MESSAGE, "xd")
}
startActivity(intent)
finish()
}
}
Also mention that the TextView omit is located in 3 different fragments but the 3 with the id omitir_swipe
Logcat:
activity_splash.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>
Try add
omitir_swipe= findViewById(R.id.omitir_swipe)
findViewById<Button>(R.id.omiti_swipe).setOnClickListener{
val intent = Intent(this, MainActivity::class.java).apply {
putExtra(EXTRA_MESSAGE, "xd")
}
startActivity(intent)
finish()
}

ImageView not appearing when button clicked

I created a small practice app which changes the image on-screen when the buttonNext is clicked. However, neither the image nor button does anything. Everything in my MainActivity looks normal for an onClickListener setup and I followed various guides to create a layout which works. But, I'm not sure why it looks so weird and does not work in the emulator.
Here is the MainActivity code I wrote so far:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setListener()
}
private fun changeImage(view: View) {
when (view.id) {
R.id.goodMorning -> view.setBackgroundResource(R.drawable.gm1)
R.id.goodMorning -> view.setBackgroundResource(R.drawable.gm2)
else -> view.setBackgroundColor(Color.LTGRAY)
}
}
private fun setListener() {
val goodMorning = findViewById<ImageView>(R.id.goodMorning)
val buttonNext = findViewById<TextView>(R.id.buttonNext)
fun setListener(){
val clickableViews: List<View> =
listOf(goodMorning, buttonNext)
for (item in clickableViews){
item.setOnClickListener() { changeImage(it) }
}
}
}
}
This is the layout xml:
<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">
<ImageView
android:id="#+id/goodMorning"
android:layout_width="404dp"
android:layout_height="562dp"
android:contentDescription="#android:string/no"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.428"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.365"
tools:srcCompat="#drawable/gm1" />
<Button
android:id="#+id/buttonNext"
style="#style/twoButtons"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:text="#string/buttonNext"
android:textSize="#dimen/box_text_size"
app:layout_constraintBaseline_toBaselineOf="#+id/buttonBack"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/buttonBack" />
<Button
android:id="#+id/buttonDownload"
style="#style/twoButtons"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:text="#string/buttonDownload"
android:textSize="#dimen/box_text_size"
app:layout_constraintBaseline_toBaselineOf="#+id/buttonBack"
app:layout_constraintEnd_toStartOf="#+id/buttonBack"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="#+id/buttonBack"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginBottom="16dp"
android:text="#string/buttonBack"
android:textColor="#android:color/black"
android:textSize="#dimen/box_text_size"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/goodMorning"
app:layout_constraintVertical_bias="0.718" />
This is what the app looks like in Pixel 2:
Any help is greatly appreciated!
change the code like this
private fun changeImage(view: View) {
val goodMorning = findViewById<ImageView>(R.id.goodMorning)
when (view.id) {
R.id.buttonBack -> view.setBackgroundResource(R.drawable.gm1)
R.id.buttonNext -> view.setBackgroundResource(R.drawable.gm2)
else -> goodMorning.setBackgroundColor(Color.LTGRAY)
}
}
private fun setListener() {
val buttonNext = findViewById<TextView>(R.id.buttonNext)
val buttonBack = findViewById<TextView>(R.id.buttonBack)
val clickableViews: List<View> =
listOf(buttonBack, buttonNext)
for (item in clickableViews){
item.setOnClickListener() { changeImage(it) }
}
}
I found out how to fix the issue:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val nextButton: Button = findViewById(R.id.buttonNext)
nextButton.setOnClickListener() { changeImage() }
}
private fun changeImage() {
// Shift through all available images
val imageOptions: ImageView = findViewById(R.id.morningImages)
val drawableResources = when (imageOptions) {
buttonNext -> R.drawable.gm1
else -> R.drawable.gm2
}
imageOptions.setImageResource(drawableResources)
// Repeat function needed
}
}
You are better off creating the clickListener at the beginning with onCreate because you will not have to create another private function which can make this issue more confusing than it really is.
Create a new variable within the changeImage function to find the ImageView. After that, make another variable called to create a when block to shift through the images available and end it with an else statement to avoid creating an error.
Set the imageResource to drawableResources so the images appear on-screen when requested.
Note: a repeat function is needed to shift through the images again once the user goes through all of them.

Categories

Resources