recyclerview shows only on the second click of another button in kotlin - android

Now, the question here, whenever I click btnCash it should directly display a row on recyclerview. But, it only does it if I clikc another button after I click btnCash.
Lets say that I want to pay 2.50. After I enter this value, I click btnCash but it doesn't display anything yet. I must click another (numeric buttons 0-9) for that display happens.
by using println I can see that when I clikc btnCash, it adds to ArrayList.
Is there any solution for this?
Why can't I put it on display at first btnCash click?
Any help arraciated.
I have payment.xml
<?xml version="1.0" encoding="utf-8"?>
<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="wrap_content"
android:layout_height="wrap_content"
android:background="#ecf0f1"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView_payment"
android:layout_width="match_parent"
android:layout_height="284dp"
android:background="#color/qtr_gray6"
android:textSize="30sp"
/>
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="280dp"
android:orientation="horizontal">
<EditText
android:id="#+id/textPayment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="end"
android:hint="00.0"
android:inputType="numberDecimal"
android:paddingRight="30dp"
android:textAlignment="textEnd"
app:layout_constraintEnd_toEndOf="parent" />
</android.support.constraint.ConstraintLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="340dp"
android:orientation="horizontal">
<Button
android:id="#+id/btnFifty"
android:layout_width="20dp"
android:layout_height="match_parent"
android:layout_margin="1dp"
android:layout_weight="0.25"
android:background="#color/qtr_primary"
android:text="£50"
android:textColor="#ecf0f1"
android:textSize="20sp" />
<Button
android:id="#+id/btnTwenty"
android:layout_width="20dp"
android:layout_height="match_parent"
android:layout_margin="1dp"
android:layout_weight="0.25"
android:background="#color/qtr_primary"
android:text="£20"
android:textColor="#ecf0f1"
android:textSize="20sp" />
<Button
android:id="#+id/btnTen"
android:layout_width="20dp"
android:layout_height="match_parent"
android:layout_margin="1dp"
android:layout_weight="0.25"
android:background="#color/qtr_primary"
android:text="£10"
android:textColor="#ecf0f1"
android:textSize="20sp" />
<Button
android:id="#+id/btnFivePound"
android:layout_width="20dp"
android:layout_height="match_parent"
android:layout_margin="1dp"
android:layout_weight="0.25"
android:background="#color/qtr_primary"
android:text="£5"
android:textColor="#ecf0f1"
android:textSize="20sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="390dp"
android:orientation="horizontal">
<Button
android:id="#+id/btnOne"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="1dp"
android:layout_weight="0.25"
android:background="#color/qtr_primary2"
android:onClick="onDigit"
android:text="1"
android:textColor="#ecf0f1"
android:textSize="20sp" />
<Button
android:id="#+id/btnTwo"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="1dp"
android:layout_weight="0.25"
android:background="#color/qtr_primary2"
android:onClick="onDigit"
android:text="2"
android:textColor="#ecf0f1"
android:textSize="20sp" />
<Button
android:id="#+id/btnThree"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="1dp"
android:layout_weight="0.25"
android:background="#color/qtr_primary2"
android:onClick="onDigit"
android:text="3"
android:textColor="#ecf0f1"
android:textSize="20sp" />
<Button
android:id="#+id/btnBack"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="1dp"
android:layout_weight="0.25"
android:background="#color/qtr_btn8"
android:onClick="onBack"
android:text="Back"
android:textColor="#ecf0f1"
android:textSize="14sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="442dp"
android:orientation="horizontal">
<Button
android:id="#+id/btnFour"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="1dp"
android:layout_weight="0.25"
android:background="#color/qtr_primary2"
android:onClick="onDigit"
android:text="4"
android:textColor="#ecf0f1"
android:textSize="20sp" />
<Button
android:id="#+id/btnFive"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="1dp"
android:layout_weight="0.25"
android:background="#color/qtr_primary2"
android:onClick="onDigit"
android:text="5"
android:textColor="#ecf0f1"
android:textSize="20sp" />
<Button
android:id="#+id/btnSix"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="1dp"
android:layout_weight="0.25"
android:background="#color/qtr_primary2"
android:onClick="onDigit"
android:text="6"
android:textColor="#ecf0f1"
android:textSize="20sp" />
<Button
android:id="#+id/btnStaff"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="1dp"
android:layout_weight="0.25"
android:background="#color/qtr_btn9"
android:onClick="onStaff"
android:text="Staff"
android:textColor="#ecf0f1"
android:textSize="14sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="495dp"
android:orientation="horizontal">
<Button
android:id="#+id/btnSeven"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="1dp"
android:layout_weight="0.25"
android:background="#color/qtr_primary2"
android:onClick="onDigit"
android:text="7"
android:textColor="#ecf0f1"
android:textSize="20sp" />
<Button
android:id="#+id/btnEight"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="1dp"
android:layout_weight="0.25"
android:background="#color/qtr_primary2"
android:onClick="onDigit"
android:text="8"
android:textColor="#ecf0f1"
android:textSize="20sp" />
<Button
android:id="#+id/btnNine"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="1dp"
android:layout_weight="0.25"
android:background="#color/qtr_primary2"
android:onClick="onDigit"
android:text="9"
android:textColor="#ecf0f1"
android:textSize="20sp" />
<Button
android:id="#+id/btnVoucher"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="1dp"
android:layout_weight="0.25"
android:background="#color/qtr_btn10"
android:onClick="onVoucher"
android:text="Voucher"
android:textColor="#ecf0f1"
android:textSize="14sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="547dp"
android:orientation="horizontal">
<Button
android:id="#+id/btnZero"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="1dp"
android:layout_weight="0.25"
android:background="#color/qtr_primary2"
android:onClick="onDigit"
android:text="0"
android:textColor="#ecf0f1"
android:textSize="20sp" />
<Button
android:id="#+id/btnClear"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="1dp"
android:layout_weight="0.25"
android:background="#color/qtr_primary2"
android:onClick="onClear"
android:text="cl"
android:textColor="#ecf0f1"
android:textSize="20sp" />
<Button
android:id="#+id/btnCard"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="1dp"
android:layout_weight="0.25"
android:background="#color/qtr_btn6"
android:onClick="onClick_Action_Function"
android:text="Card"
android:textColor="#ecf0f1"
android:textSize="30sp" />
<Button
android:id="#+id/btnCash"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="1dp"
android:layout_weight="0.25"
android:clickable="true"
android:background="#color/qtr_btn7"
android:text="Cash"
android:textColor="#ecf0f1"
android:textSize="30sp" />
</LinearLayout>
and, PaymentActivity.kt
package com.soyut.su.epos01
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.text.Editable
import android.view.View
import android.widget.Button
import android.widget.EditText
import kotlinx.android.synthetic.main.payment.*
import android.text.TextWatcher
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import java.lang.ref.WeakReference
import java.math.BigDecimal
import java.util.*
class PaymentActivity : AppCompatActivity() {
lateinit var pRecyclerView: RecyclerView
lateinit var txtInput: EditText
var lastNumeric: Boolean = false
var stateError: Boolean = false
var lastDot: Boolean = false
var list = ArrayList<Payment>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.payment)
txtInput = textPayment
txtInput.addTextChangedListener(MoneyTextWatcher(txtInput))
pRecyclerView = recyclerView_payment
pRecyclerView.layoutManager = LinearLayoutManager(this)
pRecyclerView.adapter = PaymentAdapter(this, list)
btnCash.setOnClickListener {
var paymAmnt: String = txtInput.text.toString()
list.add(Payment("Cash", paymAmnt))
for (i in list){
println(i.paymentDesc+ " - " +i.paymentAmnt)
}
}
}
fun onClick_Action_Function(view: View) {
var paymAmnt: String = txtInput.text.toString()
list.add(Payment("Card", paymAmnt))
}
fun onDigit(view: View) {
// If not, already there is a valid expression so append to it
txtInput.append((view as Button).text)
// Set the flag
lastNumeric = true
}
fun onBack(view: View) {
var sz = txtInput.text.length
println(sz)
val textString = txtInput.getText().toString()
if (textString.length > 0) {
txtInput.setText(textString.substring(0, textString.length - 1))
}
}
fun onClear(view: View) {
var sz = txtInput.text.length
txtInput.text = txtInput.text.dropLast(sz) as Editable
}
/**
* Append . to the TextView
*/
fun onDecimalPoint(view: View) {
if (lastNumeric && !stateError && !lastDot) {
txtInput.append(".")
lastNumeric = false
lastDot = true
}
}
fun onOperator(view: View) {
if (lastNumeric && !stateError) {
txtInput.append((view as Button).text)
lastNumeric = false
lastDot = false // Reset the DOT flag
}
}
inner class MoneyTextWatcher(editText: EditText) : TextWatcher {
private val editTextWeakReference: WeakReference<EditText>
init {
editTextWeakReference = WeakReference<EditText>(editText)
}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
override fun afterTextChanged(editable: Editable) {
val editText = editTextWeakReference.get() ?: return
val s = editable.toString()
if (s.isEmpty()) return
editText.removeTextChangedListener(this)
val cleanString = s.replace("[$,.]".toRegex(), "")
val parsed = BigDecimal(cleanString).setScale(2, BigDecimal.ROUND_FLOOR)
.divide(BigDecimal(100), BigDecimal.ROUND_FLOOR)
// val formatted = NumberFormat.getCurrencyInstance(Locale.UK).format(parsed)
editText.setText(parsed.toString())
editText.setSelection(parsed.toString().length)
editText.addTextChangedListener(this)
}
}
}
and,finally PaymentAdapter.kt
package com.soyut.su.epos01
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.single_payment.view.*
class PaymentAdapter(val context: Context, val items: List<Payment>) : RecyclerView.Adapter<PaymentAdapter.PaymentViewHolder>() {
override fun onBindViewHolder(p0: PaymentAdapter.PaymentViewHolder, p1: Int) {
p0.bindItems(items[p1])
}
override fun getItemId(position: Int): Long {
return super.getItemId(position)
}
override fun getItemCount(): Int {
return items.size
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PaymentViewHolder {
val inflater = LayoutInflater.from(parent.context)
val view = inflater.inflate(R.layout.single_payment, parent, false)
view.requestFocus()
return PaymentViewHolder(view)
}
inner class PaymentViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bindItems(pym: Payment) {
val textPaymentDesc = itemView.txtPaymentDescription
val textPaymentAmnt = itemView.txtPaymentAmount
textPaymentDesc.text = pym.paymentDesc
textPaymentAmnt.text = pym.paymentAmnt
}
}
}
Kind Regards

Use notifyDataSetChanged() after add, update or delete data from data set.
Try like the following
var adapter: PaymentAdapter ?=null // decleare it before onCreate()
adapter = PaymentAdapter(this, list) // here you shoule initialize you adapter
pRecyclerView.adapter = adapter // assigne your adapter to recyclerview
btnCash.setOnClickListener {
var paymAmnt: String = txtInput.text.toString()
list.add(Payment("Cash", paymAmnt))
adapter?.notifyDataSetChanged() // add this line to notify your adapter that data set is changed.
//....
}

Related

Issue with implementing View Binding in Android

I am trying to implement view binding to one of my activity. The issue is I am not able to access the views and it shows unresolved reference.
Now when I am using tools:viewBindingIgnore="true"
then there are no issues with the views and I am able to access them but then I am getting unresolved symbol for the activity class.
activity_single_movie.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"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center"
android:visibility="gone"/>
<TextView
android:id="#+id/text_error"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="Connection gone!!"
android:textColor="#color/white"
android:visibility="gone" />
<ScrollView
app:layout_constraintTop_toTopOf= "parent"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<LinearLayout
android:id="#+id/linear_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/movie_poster"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:adjustViewBounds="true"
android:layout_gravity="center"
android:scaleType="fitCenter"
android:src="#drawable/placeholder_image"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_margin="8dp" >
<TextView
android:id="#+id/movie_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="movie"
android:textStyle="bold"
android:textSize="18sp" />
<TextView
android:id="#+id/movie_tagline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="sub title"
android:textStyle="bold"
android:textSize="14sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="movie info"
android:textStyle="bold"
android:textSize="14sp" />
//Layout for Release Date
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:text="Release Date: "
android:textSize="12sp"
style="bold" />
<TextView
android:id="#+id/movie_release_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:text="2019"
android:textSize="12sp"
style="bold" />
</LinearLayout>
//Layout for Rating
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:text="Rating: "
android:textSize="12sp"
style="bold" />
<TextView
android:id="#+id/movie_rating"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:text="5/10"
android:textSize="12sp"
style="bold" />
</LinearLayout>
//Layout for Runtime
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:text="Runtime: "
android:textSize="12sp"
style="bold" />
<TextView
android:id="#+id/movie_runtime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:text="2hrs 13mins"
android:textSize="12sp"
style="bold" />
</LinearLayout>
//Layout for Budget
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:text="Budget: "
android:textSize="12sp"
style="bold" />
<TextView
android:id="#+id/movie_budget"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:text="$550Million"
android:textSize="12sp"
style="bold" />
</LinearLayout>
//Layout for revenue
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:text="Budget: "
android:textSize="12sp"
style="bold" />
<TextView
android:id="#+id/movie_revenue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:text="$550Million"
android:textSize="12sp"
style="bold" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</ScrollView>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
In SingleMovie.kt
package com.example.movieapp.ui.single_movie_details
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import com.bumptech.glide.Glide
import com.example.movieapp.R
import com.example.movieapp.data.api.POSTER_BASE_URL
import com.example.movieapp.data.api.TheMovieDBClient
import com.example.movieapp.data.api.TheMovieDBInterface
import com.example.movieapp.data.repository.NetworkState
import com.example.movieapp.data.vo.MovieDetails
import com.example.movieapp.databinding.ActivitySingleMovieBinding
import java.text.NumberFormat
import java.util.*
class SingleMovie : AppCompatActivity() {
private lateinit var viewModel: SingleMovieViewModel
private lateinit var movieRepository: MovieDetailsRepository
private lateinit var binding: ActivitySingleMovieBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySingleMovieBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
val movieId: Int = intent.getIntExtra("id", 1)
val apiService: TheMovieDBInterface = TheMovieDBClient.getClient()
movieRepository = MovieDetailsRepository(apiService)
viewModel = getViewModel(movieId)
viewModel.movieDetails.observe(this, Observer {
bindUi(it)
})
viewModel.movieDetailsNetworkState.observe(this, Observer {
binding.progress_bar.setVisibility(if (it == NetworkState.LOADING) View.VISIBLE else View.GONE)
binding.text_error.setVisibility( if(it == NetworkState.ERROR) View.VISIBLE else View.GONE)
})
}
fun bindUi(it: MovieDetails){
binding.movie_title.setText(it.title)
binding.movie_tagline.setText(it.tagline)
binding.movie_release_date.setText(it.releaseDate)
binding.movie_rating.setText(it.voteAverage.toString())
binding.movie_runtime.setText(it.runtime.toString() + "minutes")
val formatCurrency: NumberFormat = NumberFormat.getCurrencyInstance(Locale.US)
binding.movie_budget.setText(formatCurrency.format(it.budget))
binding.movie_revenue.setText(formatCurrency.format(it.revenue))
//for poster of movie
val moviePosterURL: String = POSTER_BASE_URL + it.posterPath
Glide.with(this)
.load(moviePosterURL)
.into(binding.movie_poster)
}
private fun getViewModel(movieId: Int): SingleMovieViewModel {
return ViewModelProviders.of(this, object: ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return SingleMovieViewModel(movieRepository, movieId) as T
}
}) [SingleMovieViewModel::class.java]
}
}
Errors while using tools:viewBindingIgnore="true"
Unresolved reference: ActivitySingleMovieBinding
Errors without using tools:viewBindingIgnore="true"
Unresolved reference: progress_bar
and similar for all the views
View Binding converts underscores to camelCase, the correct syntax is binding.progressBar
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center"
android:visibility="gone"/>
binding.progressBar.setVisibility(if (it == NetworkState.LOADING) View.VISIBLE else View.GONE)

Add and Remove Views in Android Dynamically in Kotlin

I modified my code by referring to the "https://www.tutorialspoint.com/add-and-remove-views-in-android-dynamically-in-kotlin". There was no error in my code, but the view added when running in the app was not visible. I have no idea what the problem is. Please help me!!
Activity to which the view is added
package com.akj.callback
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.*
import com.akj.callback.databinding.ActivitySearchSubject2Binding
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.activity_search_subject_2.*
import kotlinx.android.synthetic.main.activity_search_subject_2.to_go_check
import kotlinx.android.synthetic.main.choiced_subject_list.*
import java.util.*
class search_subject_2 : AppCompatActivity() {
lateinit var binding3:ActivitySearchSubject2Binding
private var parentLinearLayout: LinearLayout? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_search_subject_2)
parentLinearLayout = findViewById(R.id.parent_linear_layout)
binding3= ActivitySearchSubject2Binding.inflate(layoutInflater)
setContentView(binding3.root)
userList3.onItemClickListener= AdapterView.OnItemClickListener{
parent, view, position, id ->
//parent?.getItemAtPosition(position).toString()
onAddField()
}
val user = arrayOf("abc", "bcd", "cde", "def", "efg")
val userAdapter: ArrayAdapter<String> = ArrayAdapter(
this,android.R.layout.simple_list_item_1,user)
to_go_check.setOnClickListener {
val intent6=Intent(this#search_subject_2,checkthesetting::class.java)
startActivity(intent6)
}
binding3.searchView3.setOnQueryTextListener(object :androidx.appcompat.widget.SearchView.OnQueryTextListener{
override fun onQueryTextSubmit(query: String?): Boolean {
binding3.searchView3.clearFocus()
if(user.contains(query)){
userAdapter.filter.filter(query)
}
return false
}
override fun onQueryTextChange(newText: String?): Boolean {
if(newText==""){
}
else{
binding3.userList3.adapter=userAdapter
userAdapter.filter.filter(newText)
}
return false
}
})
}
fun onDelete(view: View) {
parentLinearLayout!!.removeView(view.parent as View)
}
fun onAddField() {
val inflater =
getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val rowView: View = inflater.inflate(R.layout.choiced_subject_list, null)
parentLinearLayout!!.addView(rowView, parentLinearLayout!!.childCount - 1)
Toast.makeText(applicationContext,"fdsvkgjh", Toast.LENGTH_SHORT).show()
}
}
choiced_subject_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal">
<TextView
android:id="#+id/number_edit_text"
android:text="title_fdskhdsffsd"
android:textColor="#color/black"
android:textSize="30dp"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:inputType="phone"
/>
<Button
android:id="#+id/delete_button"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_weight="1"
android:background="#android:drawable/ic_delete"
android:onClick="onDelete" />
</LinearLayout>
activity_search_subject_2.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=".search_subject_2">
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.04" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.94" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.03" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.97" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.06" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.11" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.87" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.5" />
<androidx.appcompat.widget.SearchView
android:id="#+id/searchView3"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#drawable/coner_search_bar"
android:theme="#style/AppSearchView"
app:layout_constraintBottom_toTopOf="#id/guideline6"
app:layout_constraintEnd_toEndOf="#id/guideline4"
app:layout_constraintStart_toStartOf="#id/guideline3"
app:layout_constraintTop_toBottomOf="#id/guideline5"
app:queryHint="강좌 검색"
app:iconifiedByDefault="false"
/>
<androidx.appcompat.widget.AppCompatButton
android:id="#+id/to_go_check"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintStart_toEndOf="#id/guideline3"
app:layout_constraintEnd_toStartOf="#id/guideline4"
app:layout_constraintTop_toBottomOf="#id/guideline1"
app:layout_constraintBottom_toTopOf="#id/guideline2"
app:layout_constraintVertical_bias="0.98"
android:text="확인"
android:textColor="#FFF"
android:textSize="20dp"
android:background="#drawable/coner_search_bar"
android:stateListAnimator="#null"
/>
<HorizontalScrollView
android:id="#+id/scrollView"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:scrollbars="none"
app:layout_constraintBottom_toTopOf="#+id/to_go_check"
app:layout_constraintEnd_toStartOf="#id/guideline4"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toEndOf="#id/guideline3"
>
<LinearLayout
android:id="#+id/linear_button"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="horizontal"
>
<androidx.appcompat.widget.AppCompatButton
android:id="#+id/njklsfd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:background="#drawable/search_subject_bar"
android:stateListAnimator="#null"
android:text="전공검색" />
<androidx.appcompat.widget.AppCompatButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:background="#drawable/search_subject_bar"
android:stateListAnimator="#null"
android:text="교양검색" />
<androidx.appcompat.widget.AppCompatButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:background="#drawable/search_subject_bar"
android:stateListAnimator="#null"
android:text="교수검색" />
<androidx.appcompat.widget.AppCompatButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:background="#drawable/search_subject_bar"
android:stateListAnimator="#null"
android:text="정렬" />
<androidx.appcompat.widget.AppCompatButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:background="#drawable/search_subject_bar"
android:stateListAnimator="#null"
android:text="학점:3" />
<androidx.appcompat.widget.AppCompatButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:background="#drawable/search_subject_bar"
android:stateListAnimator="#null"
android:text="학점:2" />
<androidx.appcompat.widget.AppCompatButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:background="#drawable/search_subject_bar"
android:text="학점:1"
/>
</LinearLayout>
</HorizontalScrollView>
<ListView
android:id="#+id/userList3"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="#+id/guideline8"
app:layout_constraintEnd_toStartOf="#+id/guideline4"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="#id/guideline3"
app:layout_constraintTop_toTopOf="#+id/guideline6"
app:layout_constraintVertical_bias="0.0" />
<LinearLayout
android:orientation="vertical"
android:id="#+id/parent_linear_layout"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginTop="7dp"
android:layout_marginBottom="7dp"
app:layout_constraintBottom_toTopOf="#id/scrollView"
app:layout_constraintEnd_toStartOf="#+id/guideline4"
app:layout_constraintStart_toEndOf="#id/guideline3"
app:layout_constraintTop_toBottomOf="#id/guideline8" />
</androidx.constraintlayout.widget.ConstraintLayout>
Try this:
val inflater = getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val rowView: View = inflater.inflate(R.layout.row_child_view, null, false)
Mainview.removeView(rowView)

setOnClickListener not working for button in Android Kotlin

I am trying to build a simple calculator app for android using kotlin. But setOnClickListener is not working while clicking the buttons.
MainActiviy.kt
package com.example.calculator
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
import kotlin.math.log
class MainActivity : AppCompatActivity() {
private lateinit var result:EditText
private lateinit var newNumber:EditText
private lateinit var displayOperation:TextView
private var operand1:Double?=null
private var operand2:Double=0.0
private var pendingOperation ="="
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
result = findViewById(R.id.result)
newNumber=findViewById(R.id.newNumber)
displayOperation=findViewById(R.id.displayOperation)
val button0:Button = findViewById(R.id.button0)
val button1:Button = findViewById(R.id.button1)
val button2:Button = findViewById(R.id.button2)
val button3:Button = findViewById(R.id.button3)
val button5:Button = findViewById(R.id.button5)
val button6:Button = findViewById(R.id.button6)
val button4:Button = findViewById(R.id.button4)
val button7:Button = findViewById(R.id.button7)
val button8:Button = findViewById(R.id.button8)
val button9:Button = findViewById(R.id.button9)
val buttonDot:Button = findViewById(R.id.buttonDot)
val buttonEqual:Button = findViewById(R.id.buttonEqual)
val buttonAdd:Button = findViewById(R.id.buttonAdd)
val buttonSub:Button = findViewById(R.id.buttonSub)
val buttonMul:Button = findViewById(R.id.buttonMul)
val buttonDiv:Button = findViewById(R.id.buttonDiv)
val listener = View.OnClickListener { v->
val b = v as Button
newNumber.append(b.text)
}
button0.setOnClickListener { listener }
button1.setOnClickListener { listener }
button2.setOnClickListener { listener }
button3.setOnClickListener { listener }
button4.setOnClickListener { listener }
button5.setOnClickListener { listener }
button6.setOnClickListener { listener }
button7.setOnClickListener { listener }
button8.setOnClickListener { listener }
button9.setOnClickListener { listener }
buttonDot.setOnClickListener { listener }
}
}
activity_main.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=".MainActivity">
<Button
android:id="#+id/button0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:clickable="true"
android:minWidth="48dp"
android:text="0"
app:layout_constraintStart_toStartOf="#+id/button1"
app:layout_constraintTop_toBottomOf="#+id/button1" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:minWidth="48dp"
android:text="1"
app:layout_constraintStart_toStartOf="#+id/button4"
app:layout_constraintTop_toBottomOf="#+id/button4" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:minWidth="48dp"
android:text="2"
app:layout_constraintBaseline_toBaselineOf="#+id/button1"
app:layout_constraintStart_toEndOf="#+id/button1" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:minWidth="48dp"
android:text="3"
app:layout_constraintBaseline_toBaselineOf="#+id/button2"
app:layout_constraintStart_toEndOf="#+id/button2" />
<Button
android:id="#+id/button8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:minWidth="48dp"
android:text="8"
app:layout_constraintBaseline_toBaselineOf="#+id/button7"
app:layout_constraintStart_toEndOf="#+id/button7" />
<Button
android:id="#+id/button6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:minWidth="48dp"
android:text="6"
app:layout_constraintBaseline_toBaselineOf="#+id/button5"
app:layout_constraintStart_toEndOf="#+id/button5" />
<Button
android:id="#+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:minWidth="48dp"
android:text="4"
app:layout_constraintStart_toStartOf="#+id/button7"
app:layout_constraintTop_toBottomOf="#+id/button7" />
<Button
android:id="#+id/button5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:minWidth="48dp"
android:text="5"
app:layout_constraintBaseline_toBaselineOf="#+id/button4"
app:layout_constraintStart_toEndOf="#+id/button4" />
<Button
android:id="#+id/button7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:minWidth="48dp"
android:text="7"
app:layout_constraintStart_toStartOf="#+id/newNumber"
app:layout_constraintTop_toBottomOf="#+id/newNumber" />
<Button
android:id="#+id/button9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:minWidth="48dp"
android:text="9"
app:layout_constraintBaseline_toBaselineOf="#+id/button8"
app:layout_constraintStart_toEndOf="#+id/button8" />
<Button
android:id="#+id/buttonDot"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:minWidth="48dp"
android:text="."
app:layout_constraintBaseline_toBaselineOf="#+id/button0"
app:layout_constraintStart_toEndOf="#+id/button0" />
<Button
android:id="#+id/buttonEqual"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:minWidth="48dp"
android:text="="
app:layout_constraintBaseline_toBaselineOf="#+id/buttonDot"
app:layout_constraintStart_toEndOf="#+id/buttonDot" />
<Button
android:id="#+id/buttonAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:minWidth="48dp"
android:text="+"
app:layout_constraintBaseline_toBaselineOf="#+id/buttonEqual"
app:layout_constraintStart_toEndOf="#+id/buttonEqual" />
<Button
android:id="#+id/buttonDiv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:minWidth="48dp"
android:text="/"
app:layout_constraintBaseline_toBaselineOf="#+id/button9"
app:layout_constraintStart_toEndOf="#+id/button9" />
<Button
android:id="#+id/buttonMul"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:minWidth="48dp"
android:text="*"
app:layout_constraintBaseline_toBaselineOf="#+id/button6"
app:layout_constraintStart_toEndOf="#+id/button6" />
<Button
android:id="#+id/buttonSub"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:minWidth="48dp"
android:text="-"
app:layout_constraintBaseline_toBaselineOf="#+id/button3"
app:layout_constraintStart_toEndOf="#+id/button3" />
<TextView
android:id="#+id/displayOperation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintBaseline_toBaselineOf="#+id/newNumber"
app:layout_constraintEnd_toStartOf="#+id/newNumber"
app:layout_constraintStart_toStartOf="parent" />
<EditText
android:id="#+id/result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:ems="10"
android:focusable="false"
android:focusableInTouchMode="false"
android:inputType="numberSigned|numberDecimal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="#+id/newNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:ems="10"
android:inputType="numberSigned|text|numberDecimal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/result" />
</androidx.constraintlayout.widget.ConstraintLayout>
This is because you're not setting any listener to the buttons, but you're defining new listeners that don't invoke any method
This will work:
button.setOnClickListener(listener)
This will work too, but here you have 2 listeners: the original one invoked by another one:
button.setOnClickListener{ listener.onClick(it) }
If you really do not want to implement View.OnClickListener you just need to trigger your local listener on button click.
e.g. for button0 make it
button0.setOnClickListener { listener.onClick(it) }
Data binding can reduce the findViewById lines. My latest environment provides data binding for kotlin by default.
first of all, you don't need to use findViewById in Kotlin. You can use it directly using id you provide in xml.
Use click listener like below
button6.setOnClickListener(object :View.OnClickListener{
// do button click
})
For multiple button click you can implement View.OnClickListener in activity and use it like.
class MainActivity : AppCompatActivity(),View.OnClickListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button6.setOnClickListener = this
}
override fun onClick(v: View?) {
when (v?.id) {
R.id.button6 -> {
// do button click
}
}
}
}
If you don't want to set setOnClickListener for every button you can use databinding for that as well. It reduce lots of code.

Create multiple sets of plus and minus buttons with TextView on same page of App (Kotlin)

I have two controls that i can increase or decrease an integer. I click on either the first or second set of plus and minus buttons,despite being separate functions, it'll display the Integers on both outputs. For example if I click on the plus and minus button for the integer_number_1, it'll display the numbers on both the integer_number_1 and integer_number_2 outputs/TextView.
How do I fix this??? I've so many different ways and none of them worked.
Here's my xml section:
<?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">
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="56dp"
android:layout_marginBottom="549dp"
android:orientation="horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<Button
android:id="#+id/decrease_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="-" />
<TextView
android:id="#+id/integer_number_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="40dp"
android:layout_marginTop="16dp"
android:layout_marginRight="40dp"
android:layout_marginBottom="16dp"
android:inputType="number"
android:text="0"
android:textSize="70sp"
android:textStyle="bold" />
<Button
android:id="#+id/increase_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+" />
</LinearLayout>
<Button
android:id="#+id/decrease_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="-"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/integer_number_2"
app:layout_constraintHorizontal_bias="0.513"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/linearLayout"
app:layout_constraintVertical_bias="0.317" />
<Button
android:id="#+id/increase_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.579"
app:layout_constraintStart_toEndOf="#+id/integer_number_2"
app:layout_constraintTop_toBottomOf="#+id/linearLayout"
app:layout_constraintVertical_bias="0.313" />
<TextView
android:id="#+id/integer_number_2"
android:layout_width="46dp"
android:layout_height="99dp"
android:layout_marginStart="46dp"
android:layout_marginLeft="46dp"
android:inputType="number"
android:text="0"
android:textSize="70sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.426"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/linearLayout"
app:layout_constraintVertical_bias="0.297" />
</androidx.constraintlayout.widget.ConstraintLayout>
And here's my kt file:
package com.example.plus_and_minus_input
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
increase_1.setOnClickListener { increaseInteger1() }
decrease_1.setOnClickListener { decreaseInteger1() }
increase_2.setOnClickListener { increaseInteger2() }
decrease_2.setOnClickListener { decreaseInteger2() }
}
fun increaseInteger1() {
display(integer_number_1.text.toString().toInt() + 1)
}
fun decreaseInteger1() {
display(integer_number_1.text.toString().toInt() - 1)
}
fun increaseInteger2() {
display(integer_number_2.text.toString().toInt() + 1)
}
fun decreaseInteger2() {
display(integer_number_2.text.toString().toInt() - 1)
}
private fun display(number: Int) {
integer_number_1.setText("$number")
integer_number_2.setText("$number")
}
}
I think you need to separate this following display methods.
private fun display(number: Int) {
integer_number_1.setText("$number")
integer_number_2.setText("$number")
}
to
private fun display_number_1(number: Int) {
integer_number_1.setText("$number")
}
and
private fun display_number_2(number: Int) {
integer_number_2.setText("$number")
}

Kotlin : same fragment, children with same tag

In my fragment, I have two linear layout with the same tag "result". Inside theses linear layouts, I have another layout with the tag "toggle" and a button with the tag "toggleButton".
I want that : when I click on my button, it toggle the linear layout "toggle" of its linear layout parent "result"
But when I do this :
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val root = rootLayoutResultSearch
root.findViewWithTag<Button>("toToggleButton")
val buttonToggle = view.findViewWithTag<Button>("toToggleButton")
buttonToggle.setOnClickListener{
Log.i(TAG, "click")
val toggle = view.findViewWithTag<LinearLayout>("toToggle")
if(toggle.visibility == View.GONE){
toggle.visibility = View.VISIBLE
}else{
toggle.visibility = View.GONE
}
}
}
it's working only for my first linear layout "result". When I click on my second button, it's not doing anything
Here the xml of the layouts "result" (I only post the first, the second is the exact same one)
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:tag="result"
android:contentDescription="result">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="35dp"
android:background="#drawable/whit_bg_and_shadow"
android:tag="visibleNotChangeable"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
style="#style/hoursSearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight=".1"
android:fontFamily="#font/rubik_medium_italic"
android:tag="heureDepart"
android:text="#string/fillHoursRecherche1"
android:textStyle="italic" />
<TextView
style="#style/citySearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_weight=".9"
android:fontFamily="#font/rubik_medium"
android:tag="villeDepart"
android:text="#string/fillVilleRecherche1"
android:textSize="18sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
style="#style/hoursSearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight=".1"
android:fontFamily="#font/rubik_medium_italic"
android:tag="heureDepart"
android:text="#string/fillHoursRecherche2"
android:textFontWeight="500"
android:textStyle="italic" />
<TextView
style="#style/citySearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_weight=".9"
android:fontFamily="#font/rubik_medium"
android:tag="villeDepart"
android:text="#string/fillVilleRecherche2"
android:textSize="18sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="end"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:fontFamily="#font/roboto"
android:tag="villeArrivee"
android:text="#string/jourCircuRecherche" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/roboto"
android:tag="villeArrivee"
android:text="#string/fillJourCircuRecherche" />
</LinearLayout>
<View style="#style/HorizontalLine" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/bus" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginStart="15dp"
android:background="#drawable/dark_blue_rectangle"
android:text="3"
android:textColor="#color/colorWhite" />
</LinearLayout>
<View style="#style/HorizontalLine" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:layout_width="20dp"
android:layout_height="20dp"
android:src="#drawable/horaire" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginStart="15dp"
android:fontFamily="#font/roboto"
android:text="#string/fillTempsRecherche" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="35dp"
android:background="#drawable/gray_bg"
android:visibility="gone"
android:tag="toToggle"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
style="#style/hoursSearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight=".1"
android:fontFamily="#font/rubik_medium_italic"
android:tag="heureDepart"
android:text="#string/fillHoursRecherche1"
android:textStyle="italic" />
<TextView
style="#style/citySearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_weight=".9"
android:fontFamily="#font/rubik_medium"
android:tag="villeDepart"
android:text="#string/fillVilleRecherche1"
android:textSize="18sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
style="#style/hoursSearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight=".1"
android:fontFamily="#font/rubik_medium_italic"
android:tag="heureDepart"
android:text="#string/fillHoursRecherche2"
android:textFontWeight="500"
android:textStyle="italic" />
<TextView
style="#style/citySearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_weight=".9"
android:fontFamily="#font/rubik_medium"
android:tag="villeDepart"
android:text="#string/fillVilleRecherche2"
android:textSize="18sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="end"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:fontFamily="#font/roboto"
android:tag="villeArrivee"
android:text="#string/jourCircuRecherche" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/roboto"
android:tag="villeArrivee"
android:text="#string/fillJourCircuRecherche" />
</LinearLayout>
<View style="#style/HorizontalLine" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/bus" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginStart="15dp"
android:background="#drawable/dark_blue_rectangle"
android:text="3"
android:textColor="#color/colorWhite" />
</LinearLayout>
<View style="#style/HorizontalLine" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:layout_width="20dp"
android:layout_height="20dp"
android:src="#drawable/horaire" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginStart="15dp"
android:fontFamily="#font/roboto"
android:text="#string/fillTempsRecherche" />
</LinearLayout>
</LinearLayout>
<Button
android:id="#+id/ToggleSearchResult"
android:layout_width="40dp"
android:layout_height="40dp"
android:background="#drawable/arrow_down_blue_circle"
android:layout_gravity="center"
android:layout_marginTop="-20dp"
android:tag="toToggleButton"
/>
</LinearLayout>
Okay, I've thrown together a quick idea of what I think you want to accomplish. It excludes all the error and consistency checking one would normally want to do.
package com.example.toggler
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.widget.LinearLayout
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val list = arrayListOf<View>()
root_View.findViewsWithText(list, "toToggleButton", View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION)
list.forEach { button ->
button.setOnClickListener { v: View ->
val viewParent = v.parent
if (viewParent is LinearLayout) {
val taggedView = viewParent.findViewWithTag<View>("toggle")
taggedView.visibility = when {
taggedView.visibility == View.GONE -> View.VISIBLE
else -> View.GONE
}
}
}
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/root_View"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:contentDescription="toToggleButton"
android:tag="toToggleButton"
android:text="toggle"
tools:ignore="HardcodedText" />
<View
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#F44336"
android:tag="toggle" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:contentDescription="toToggleButton"
android:tag="toToggleButton"
android:text="toggle"
tools:ignore="HardcodedText" />
<View
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#9C27B0"
android:tag="toggle" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:contentDescription="toToggleButton"
android:tag="toToggleButton"
android:text="toggle"
tools:ignore="HardcodedText" />
<View
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#FFEB3B"
android:tag="toggle" />
</LinearLayout>
</LinearLayout>
[EDIT]
Or, if you prefer to use tags:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
root_View.findViewsWithTag("toToggleButton").forEach { button ->
button.setOnClickListener { v: View ->
val viewParent = v.parent
if (viewParent is LinearLayout) {
val taggedView = viewParent.findViewWithTag<View>("toggle")
taggedView.visibility = when {
taggedView.visibility == View.GONE -> View.VISIBLE
else -> View.GONE
}
}
}
}
}
}
private fun ViewGroup.findViewsWithTag(tag: String): Sequence<View> {
return sequence {
for (index in 0 until childCount) {
val child = getChildAt(index)
when (child) {
is ViewGroup -> yieldAll(child.findViewsWithTag(tag))
is View -> if (child.tag == tag) yield(child)
}
}
}
}

Categories

Resources