<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<import type="android.view.View" />
<variable
name="notificationResponse"
type="myms.models.NotificationResponse"/>
</data>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
...........
<TextView
android:id="#+id/tv_empty_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/_12dp"
android:layout_marginRight="#dimen/_12dp"
android:minHeight="#dimen/_60dp"
android:gravity="center"
android:textSize="#dimen/_18sp"
android:textStyle="bold"
android:text="No Message"
android:background="#color/white"
android:visibility="#{notificationResponse.payloads.size() > 0 ? View.GONE : View.VISIBLE}"/>
......
</FrameLayout>
</layout>
What i want to achieve is that by default the view should be GONE and after the async call in my code where i actually bind the notificationResponse object it should decide whether to show or hide the view.
The Interpretation of the code you have written android:visibility="#{notificationResponse.payloads.size() > 0 ? View.GONE : View.VISIBLE}" is
When your list size is having more than one data you want to hide that TextView and in other case you want to show it.
Not when you are calling your API, your list size will definitely less than or equal 0 so it will not be visible.
Solution :
Pass some variable which indicates API is still calling in background and when API call is done, set that variable to false.
android:visibility="#{notificationResponse.payloads.size() > 0 || !loading ? View.GONE : View.VISIBLE}"
It means if your list size is more than one and API call is done, TextView should hide.
By default value of loading should be false, when you calling API change that value to true and when API call is done again set it to false.
In fragment/activity you could create field int itemsCount = 0 and after you got a response set the itemsCount = response.payloads.size() and in the xml set itemCount instead of NotificationResponse.
Actually you have to set your new variable in the binding to make an effect on view. It's mean that if you want to achive you result without changing you xml just set new List yo your variable and after get a response set list from response.
EDIT
first way (according to comments below) is like this:
public void setLoading(boolean loading) {
isLoading = loading;
notifyPropertyChanged(BR._all);
}
and
notifyPropertyChanged(BR.loading);
ref
But, there is an easier way of doing this, I would have done it the following way:
first change this line in your view
android:visibility="#{notificationResponse.payloads.size() > 0 ? View.GONE : View.VISIBLE}"/>
to
android:visibility="gone"/>
And then in your AsyncTask add something like this:
protected void onPostExecute(Boolean toBeShown) {
if(toBeShown){
tvEmptyView.setVisibility(View.VISIBLE);
}else{
tvEmptyView.setVisibility(View.GONE);
}
}
Another option would be to use a binding adapter.
#BindingAdapter("viewVisibility")
fun bindViewVisibility(view: View, shouldShow: Boolean) {
view.let {
if (shouldShow) {
it.visibility = View.VISIBLE
} else {
it.visibility = View.GONE
}
}
}
And in the layout:
<androidx.constraintlayout.widget.ConstraintLayout
...
viewVisibility="#{viewModel.showError}"
...>
</androidx.constraintlayout.widget.ConstraintLayout>
Related
Good morning, community, I have the following case, I have 1 list of questions with their respective YES/NO answers, which are the checkboxes, what is complicating me is how I can apply 1 validation that only allows marking 1 answer (yes or no), in turn save that answer with its respective position and then save it in a DB.
this is my adapter(preusoadapter.kt)
class preusoadapter(
private val context : Context,
private val listpreguntaspreuso: ArrayList<epreguntas>
) : RecyclerView.Adapter<preusoadapter.PreUsoViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PreUsoViewHolder {
val layoutInflater = LayoutInflater.from(context)
return PreUsoViewHolder(layoutInflater.inflate(R.layout.activity_estructura_listapreuso, parent, false)
)
}
override fun onBindViewHolder(holder: PreUsoViewHolder, position: Int) {
val item = listpreguntaspreuso[position]
holder.render(item)
holder.displayChecked(item.answer)
if (position == 2) {
holder.displayAnswers(setOf(Answer.IVSS, Answer.DSS))
} else if (position == 6) {
holder.displayAnswers(setOf(Answer.FRESERV, Answer.FREDMANO))
} else if (position == 14) {
holder.displayAnswers(setOf(Answer.NA, Answer.SI, Answer.NO))
} else if (position == 18) {
holder.displayAnswers(setOf(Answer.NA, Answer.SI, Answer.NO))
} else if (position == 22) {
holder.displayAnswers(setOf(Answer.NA, Answer.SI, Answer.NO))
} else if (position == 25) {
holder.displayAnswers(setOf(Answer.NA, Answer.SI, Answer.NO))
}
}
override fun getItemCount(): Int = listpreguntaspreuso.size
//CLASE INTERNA PREUSOVIEWHOLDER//
inner class PreUsoViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val binding = ActivityEstructuraListapreusoBinding.bind(view)
private val idpregunta = view.findViewById<TextView>(R.id.txtidpregunta)
private val numeropregunta = view.findViewById<TextView>(R.id.txtnumeropregunta)
private val pregunta = view.findViewById<TextView>(R.id.txtpreguntas)
private val imgestado = view.findViewById<ImageView>(R.id.icosemaforo)
fun render (epreguntas: epreguntas){
idpregunta.text = epreguntas.id_pregunta
numeropregunta.text = epreguntas.num_pregunta
pregunta.text = epreguntas.pregunta
Glide.with(imgestado.context).load(epreguntas.icono_estado).into(imgestado)
}
private val checkboxAnswers = mapOf(
binding.chbksi to Answer.SI,
binding.chbkno to Answer.NO,
binding.chbkna to Answer.NA,
binding.chbkIVSS to Answer.IVSS,
binding.chbkDSS to Answer.DSS,
binding.chbkFSERV to Answer.FRESERV,
binding.chbkfmano to Answer.FREDMANO
)
init {
// set the listener on all the checkboxes
checkboxAnswers.keys.forEach { checkbox ->
checkbox.setOnClickListener { handleCheckboxClick(checkbox) }
}
}
// A function that handles all the checkboxes
private fun handleCheckboxClick(checkbox: CheckBox) {
// get the item for the position the VH is displaying
val item = listpreguntaspreuso[adapterPosition]
// update the item's checked state with the Answer associated with this checkbox
// If it's just been -unchecked-, then that means nothing is checked
checkboxAnswers[checkbox]?.let { answer ->
item.answer = if (!checkbox.isChecked) null else answer
// remember to notify the adapter (so it can redisplay and uncheck any other boxes)
notifyItemChanged(adapterPosition)
}
}
fun displayChecked(answer: Answer?) {
// set the checked state for all the boxes, checked if it matches the answer
// and unchecked otherwise.
// Setting every box either way clears any old state from the last displayed item
checkboxAnswers.forEach { (checkbox, answerType) ->
checkbox.isChecked = answerType == answer
}
}
fun displayAnswers(answers: Collection<Answer>) {
// iterate over each checkbox/answer pair, hiding or displaying as appropriate
checkboxAnswers.forEach { (checkbox, answerType) ->
checkbox.visibility = if (answerType in answers) View.VISIBLE else View.GONE
}
}
}
}
and this is my class epreguntas.kt
class epreguntas(
var id_pregunta: String,
var num_pregunta: String,
var pregunta : String,
var icono_estado: String,
var checkvalor: Boolean = false,
var answer: Answer? = null
) {
}
this is my structure i use for my recylcview
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:animateLayoutChanges="true"
app:cardCornerRadius="2dp"
app:cardElevation="4dp"
app:cardUseCompatPadding="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:animateLayoutChanges="true"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/icosemaforo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="#drawable/ic_android" />
</RelativeLayout>
<LinearLayout
android:id="#+id/contenedor_categoria1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:orientation="vertical"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<TextView
android:id="#+id/txtnumeropregunta"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_alignParentTop="true"
android:text="N°"
android:textSize="14sp"
android:textStyle="bold" />
<TextView
android:id="#+id/txtpreguntas"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="20dp"
android:layout_toStartOf="#+id/contenedorcheck"
android:textSize="14sp"
android:layout_toEndOf="#+id/txtnumeropregunta"
android:textStyle="bold"
android:text="Preguntas" />
<LinearLayout
android:id="#+id/contenedorcheck"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:paddingEnd="20dp"
>
<CheckBox
android:id="#+id/chbksi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="#string/check_si" />
<CheckBox
android:id="#+id/chbkIVSS"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:visibility="gone"
android:text="#string/check_IVSS" />
<CheckBox
android:id="#+id/chbkFSERV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:visibility="gone"
android:text="#string/check_freserv" />
<CheckBox
android:id="#+id/chbkno"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="10dp"
android:text="#string/check_no" />
<CheckBox
android:id="#+id/chbkfmano"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:layout_marginEnd="10dp"
android:text="#string/check_fredmano" />
<CheckBox
android:id="#+id/chbkDSS"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:layout_marginEnd="10dp"
android:text="#string/check_DSS" />
<CheckBox
android:id="#+id/chbkna"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:layout_marginEnd="10dp"
android:text="#string/check_na" />
</LinearLayout>
</RelativeLayout>
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
It complies with selecting 1 box and unchecking the other, but I realize that when I check the box for question 1 (yes) another question overlaps and my question 1 is hidden, and I see that in some questions the YES/NO/ NA up to IVSS and DSS
example
Like Tenfour04 says, RadioButtons in a RadioGroup would handle the "only one thing can be selected" functionality. (You'd need a different listener to handle its button id has been selected callbacks.)
But since you're already storing the checked state and displaying it, you can handle that yourself - you just need a way to ensure when one checkbox is checked, the others are stored as unchecked.
An easy way to do that is to store an Int which represents the checkbox that's selected. Say 0 for the first, 1 for the second, and a negative number for none. Because each number represents one checked item, by changing the number you're "unchecking" the others.
If you want to store that in your data object (like with checkvaloryes) you can just do:
class epreguntas(
var id_pregunta: String,
...
var checkvaloryes: Boolean = false,
var id_answer: Int
)
Then your checkbox click listeners just have to store the appropriate value, and in onBindHolder you enable the selected checkbox and disable all the others.
This is basically what using a RadioGroup involves too - you get a button ID when the selection changes (-1 for no selection), you store that, and when you display it you fetch that stored ID and set it on the RadioGroup.
The automatic deselection of other buttons (in single-selection mode) is nice and convenient, but setting the current button in onBindViewHolder will trigger the OnCheckedChangedListener and you can get stuck in a loop, so you'd need to avoid that. One way is to only update your stored value (and notify the adapter of the change) if the current selection ID is different to the stored one.
But you can also use checkboxes and click listeners like you already are, you just have to handle their state yourself. Here's a bit of a long explanation of one way to do it, but it's partly about solving other problems you're probably going to run into.
I'm gonna complicate things a bit, because I feel like it will help you out once you understand what's happening - you have a few things to wrangle here. I'm just posting this as one way to approach that store and display problem.
First, I think it would be a good idea to define your options somewhere. Since you have a fixed set of checkboxes, there's a fixed set of answers, right? You could define those with an enum:
enum class Answer {
SI, NO, IVSS, FRESERV, FREDMANO, DSS, NA
}
And you could store that in your data:
class epreguntas(
...
var answer: Answer? = null // using null for 'no answer selected'
)
(You can use that enum elsewhere in your app too - it means your answer data is in a useful data structure, and it's not tied to some detail about your list display, like what order the checkboxes happen to be added in the layout. If you need to turn these enum constants into an Int, e.g. for storage, you can use their ordinal property)
Now you can connect those responses to the checkboxes that represent them. We could do that in the ViewHolder class:
class PreUsoViewHolder(view: View) : RecyclerView.ViewHolder(view) {
...
// create an answer type lookup for each checkbox in the ViewHolder instance
// I'm going to use your binding object since you have it!
val checkboxAnswers = mapOf(
binding.chbksi to SI,
binding.chbkno to NO,
...
)
That checkboxAnswers map acts as two things - it's a lookup that links each CheckBox in the layout to a specific answer type, and the keys act as a collection of all your CheckBox views, so you can easily do things to all of them together.
Now you can create a click listener that checks which View was clicked, get the matching Answer, and set it:
// I've made this an -inner- class, and it need to be nested inside your Adapter class
// This gives the ViewHolder access to stuff inside the adapter, i.e. listpreguntaspreuso
inner class PreUsoViewHolder(view: View) : RecyclerView.ViewHolder(view) {
init {
...
// set the listener on all the checkboxes
checkboxAnswers.keys.forEach { checkbox ->
checkbox.setOnClickListener { handleCheckboxClick(checkbox) }
}
// A function that handles all the checkboxes
private fun handleCheckboxClick(checkbox: CheckBox) {
// get the item for the position the VH is displaying
val item = listpreguntaspreuso[adapterPosition]
// update the item's checked state with the Answer associated with this checkbox
// If it's just been -unchecked-, then that means nothing is checked
checkboxAnswers[checkbox]?.let { answer ->
item.answer = if (!checkbox.isChecked) null else answer
// remember to notify the adapter (so it can redisplay and uncheck any other boxes)
notifyItemChanged(adapterPosition)
}
}
This relies on you using a click listener, not a checkedChanged listener, because setting checked state in onBindViewHolder (when you're clearing checkboxes) will trigger that checkedChanged listener. A click listener only fires when the user is the one checking or unchecking a box.
So now you have a click listener that sets the appropriate Answer value for an item. To display it, we could put another function in the ViewHolder:
fun displayChecked(answer: Answer?) {
// set the checked state for all the boxes, checked if it matches the answer
// and unchecked otherwise.
// Setting every box either way clears any old state from the last displayed item
checkboxAnswers.forEach { (checkbox, answerType) ->
checkbox.isChecked = answerType == answer
}
}
And now you can call that from onBindViewHolder:
override fun onBindViewHolder(holder: PreUsoViewHolder, position: Int) {
val item = listpreguntaspreuso[position]
holder.render(item)
holder.displayChecked(item.answer)
The other reason for doing things this way, is I think your code to make stuff visible/invisible is broken:
else if (position == 14){
holder.itemView.chbkna.visibility = View.VISIBLE
}
This kind of thing won't work - all you're doing is saying "for item 14, make this box visible" - it says nothing about which of the other boxes should be visible, and which should be hidden. You'll have stuff randomly shown or hidden depending on which item happened to be displayed in that ViewHolder before. You need to explicitly say what should be displayed, every time onBindViewHolder runs.
You can do that with a similar function to the displayChecked one we just wrote:
inner class PreUsoViewHolder(view: View) : RecyclerView.ViewHolder(view) {
...
// provide a list of the answers that should be shown
fun displayAnswers(answers: Collection<Answer>) {
// iterate over each checkbox/answer pair, hiding or displaying as appropriate
checkboxAnswers.forEach { (checkbox, answerType) ->
checkbox.visibility = if (answerType in answers) VISIBLE else GONE
}
}
Now you can easily update your displayed boxes in onBindViewHolder:
else if (position == 14){
holder.displayAnswers(setOf(NA, SI, NO))
}
And even better, you could create groups of answer types associated with the question in the data. So instead of hardcoding by position, you can just pull the required types out of the item itself
class epreguntas(
...
answerTypes: Set<Answer>
// onBindViewHolder
holder.displayAnswers(item.answerTypes)
You could even create preset lists for different types of question, like val yesNo = setOf(SI, NO) (or an enum) and reuse those when defining your questions - there are probably only a few combos you're using anyway!
I hope that wasn't too complicated, and the organisation ideas (and the benefits they can give you) make sense. A RadioGroup is simpler, but with the other stuff you'll probably have to deal with, I feel like this is a useful general approach
So I'd like to make a function that changes the tint of the view that is calling the function.
I'm pretty sure I got the tint part down I'm just not quite sure how or where I need to define this function so that I can either select it as the onClick method in the built-in properties menu or I can reference it in the xml file(preferably the former).
Right now I have the function in the MainActivity.kt file inside the class and I selected the function on all the different views in the properties menu but when I run the app and actually click on of these views I get a crash saying "Could not find method in parent or ancestor Context for android:onClick attribute"
I would really appreciate some help with this, thanks in advance!
You can set the same on click listener to multiple views.
val tintChanger = View.OnClickListener { view ->
println("View with id=${view.id} clicked")
changeTintOf(view as ImageView)
}
imageViewOne.setOnClickListener(tintChanger)
imageViewTwo.setOnClickListener(tintChanger)
imageViewThree.setOnClickListener(tintChanger)
How to set on click listener to views without knowing their ids?
val imageContainerLayout = findViewById<LinearLayout>(R.id.imageContainer)
// val imageContainerLayout = binding.imageContainer
imageContainerLayout.children.forEach {
it.setOnClickListener(tintChanger)
}
// xml
<LinearLayout
android:id="#+id/imageContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<ImageView ... /> // without android:id set
<ImageView ... /> // without android:id set
<ImageView ... /> // without android:id set
</LinearLayout>
Not preferred way nowadays but if you want to set a click listener on your view by xml, your activity should contain a public method changeTintOnClick with an argument view: View.
// MainActivity.kt
fun changeTintOnClick(view: View) {
println("View click listener set by XML")
println("View clickView with id=${view.id} clicked")
changeTintOf(view as ImageView)
}
private fun changeTintOf(view: ImageView) {
// your implementation for tint
}
<ImageView ...
android:onClick="changeTintOnClick"
/>
One way you can pull this of is placing an OnClickListener extension on your main activity class and set all of the views with an id and tag to reference later.
class MainActivity : AppCompatActivity(), View.OnClickListener{ /*Extend class to conformalso to View.OnClickListsner*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
//Let's say you have two or more views to use.
//You want to include the same listener to all opf the same buttons you want to use
findViewById<Button>(R.id.myelementone).setOnClickListener(this)
findViewById<Button>(R.id.myelementTwo).setOnClickListener(this)
override fun onClick(v: View) {
switch(v.tag){
case "myelementonetag":
//Do something
break;
case "myelementtwotag"
//Do something else
break;
default:
//If no tags match the clicked item
break;
}
}
}
The only thing you really need to do in XML is set the id of the element and the tag of the elements like this (using onClick in XML is no longer best practice and advised that it should not be used anymore. Dont forget to keep they styling for you own button!):
<Button
android:id="#+id/myelementone"
tag="myelementonetag"/>
<Button
android:id="#+id/myelementone"
tag="myelementonetag"/>
If you need a little more on how this works, here is another StackOverflow question that was answered with all best ways to implement click functions: Android - How to achieve setOnClickListener in Kotlin?
I am confused by a certain inconsistency in my code, where only part of the data is loading. I am trying to set up a grid of TextViews in my fragment, which read from a list variable called board on the ViewModel for that fragment. The TextView text is set as board[n].text from the view model, where n is its index in the list, and this loads just fine. I am also trying to set the TextView background to one of three background resources, which are saved as an int board[n].marking on the view model.
This does not work. It seems that it is trying to load the background for each TextView before board has been fully initialized in the view model, but it does not seem to try to do the same for the TextView text. Here are the relevant parts of my code. First, the XML layout:
<?xml version="1.0" encoding="utf-8"?>
<layout
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"
tools:context=".screens.game.GameFragment">
<data>
<import type="android.view.View"/>
<variable
name="gameViewModel"
type="com.example.mygametitle.screens.game.GameViewModel" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
(...)
<TextView
android:id="#+id/field13"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginTop="#dimen/board_vertical_margin"
android:background="#{gameViewModel.board[2].marking}"
android:onClick="#{ () -> gameViewModel.openGameDialog(2, field13)}"
android:text="#{gameViewModel.board[2].text}"
(...)
There are 25 fields like that. All of the text loads properly, but none of the background images load. If instead I hardcode the background I want, as such, it loads properly:
android:background="#drawable/board_fieldbackground_checked" . This won't work for me though, as I need to read what each entry's background is upon startup--they don't all start checked.
On the view model, board is made by reading a set of 25 entries from a Room database, each including (among other info) a text string and a marking int. These all update properly--if I use a debug function to print out the contents of my board, they all have the proper text and marking upon closing and reopening the fragment. When the fragment opens, all the text is correct, but the backgrounds are not. Any ideas on why my backgrounds aren't loading the same way the text is?
Here's some of the relevant viewmodel code:
class GameViewModel(
val database: BoardDatabaseDao,
application: Application,
val boardTitle: String) : AndroidViewModel(application) {
val BG_UNMARKED = R.drawable.board_fieldbackground_bordered
val BG_CHECKED = R.drawable.board_fieldbackground_checked
val BG_MISSED = R.drawable.board_fieldbackground_missed
private val thisBoardEntries = MutableLiveData<List<BoardField>?>()
private val _board = MutableLiveData<List<BoardField>>()
val board: LiveData<List<BoardField>>
get() = _board
private suspend fun getEntries() : List<BoardField>? {
Log.i("GameViewModel", "Running database.getFromParent(boardTitle), function getEntries().")
val entries = database.getFromParent(boardTitle)
return entries
}
init {
viewModelScope.launch {
Log.i("GameViewModel", "Start viewModelScope.launch on init block.")
thisBoardEntries.value = getEntries()
if (thisBoardEntries.value?.isEmpty()!!) {
Log.i(
"GameViewModel",
"allEntries.value is EMPTY, seemingly: ${thisBoardEntries.value}, should be empty"
)
} else {
Log.i(
"GameViewModel",
"allEntries.value is NOT empty, seemingly: ${thisBoardEntries.value}, should be size 25"
)
_board.value = thisBoardEntries.value
}
}
}
fun markFieldMissed(index: Int, view: TextView) {
Log.i("GameViewModel", "My Textview looks like this: $view")
_board.value!![index].marking = BG_MISSED
view.setBackgroundResource(BG_MISSED)
Log.i("GameViewModel", "Set background to $BG_MISSED")
val color = getColor(getApplication(), R.color.white_text_color)
view.setTextColor(color)
viewModelScope.launch {
val markedField = getEntryAtIndex(boardTitle, convertIndexToLocation(index))
Log.i("GameViewModel", "I think markedField is $markedField")
if (markedField != null) {
markedField.marking = BG_MISSED
update(markedField)
Log.i("GameViewModel", "Updated field with $BG_MISSED marking on DB: $markedField")
}
}
}
fun markFieldChecked(index: Int, view: TextView) {
_board.value!![index].marking = BG_CHECKED
view.setBackgroundResource(BG_CHECKED)
Log.i("GameViewModel", "Set background to $BG_CHECKED")
val color = getColor(getApplication(), R.color.white_text_color)
view.setTextColor(color)
viewModelScope.launch {
val markedField = getEntryAtIndex(boardTitle, convertIndexToLocation(index))
Log.i("GameViewModel", "I think markedField is $markedField")
if (markedField != null) {
markedField.marking = BG_CHECKED
update(markedField)
Log.i("GameViewModel", "Updated field with $BG_CHECKED marking on DB: $markedField")
}
}
}
fun debugPrintEntries() {
Log.i("GameViewModel", "DebugPrintEntries function: ${_board.value}")
}
(2020-11-05) Edit 1: Part of the issue was indeed a resource not being read as such. I made the following additions/changes in my layout XML, which gets me a bit further:
<data>
<import type="androidx.core.content.ContextCompat"/>
(...)
</data>
<TextView
(...)
android:background="#{ContextCompat.getDrawable(context, gameViewModel.BG_CHECKED)}"
(...)
With a hardcoded resource for BG_CHECKED as my background image, everything loads and displays nicely. The problem is once again that the background is not read from board[4].marking (which contains BG_CHECKED as its value), although the text has no problem being read from board[4].text
The following replacement in the layout XML does not work, causing an exception: Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x0 with the line
android:background="#{ContextCompat.getDrawable(context, gameViewModel.board[4].marking)}"
I haven't used data binding, but I think it might be because you're just providing an Int as the background, which happens to represent a resource ID - but the data binding doesn't know that, so it doesn't know it needs to resolve it to a drawable value in resources? When you set it manually you're explicitly telling it to do that by using the #drawable syntax
Here's a blog where someone runs into something similar (well that situation anyway, but with colours) - their second solution is to add a ContextCompat import to the data block, and then use that to do aContextCompat.getColor lookup in the data binding expression. Maybe you could do something similar to get the drawable you need
I'm using a RecyclerView with LinearLayout Manager and Horizontal orientation.
It's to be used on a TV app, so it needs to be navigated with the dpad. But whenever I go do the end and come back it get stuck on the last one. See photo:
The selected ItemView is the first, but it won't go to the center. if you go to the right and the come back it will show fully.
the code:
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="320dp"
app:layout_constraintBottom_toTopOf="#+id/tv_mini_player_view_placeholder"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/carrier_image_card"
app:layout_constraintVertical_bias="0.10">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="#dimen/margin_start_tv_home"
android:background="#null"
android:clipToPadding="false"
android:orientation="horizontal"
android:padding="#dimen/margin_medium_big"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
tools:context=".android.screens.auth.SelectCarrierActivity"
tools:listitem="#layout/imagecardview_station" />
</androidx.core.widget.NestedScrollView>
One little thing I observed is the layout World Hits didn't adjust the label size. When selected these layouts show a description which makes the transparent grey box larger to acommodate. It's a "View.GONE" change on the description label. So the last selected layout the description disappeared but the layout didn't readjusted. The code for the View Holder part is below:
inner class StationViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val mainImageView: ImageView by lazy { itemView.findViewById<ImageView>(R.id.main_image) }
val titleView: TextView by lazy { itemView.findViewById<TextView>(R.id.title_text) }
val descriptionView: TextView by lazy { itemView.findViewById<TextView>(R.id.description_text) }
init {
val frameLayout = itemView.findViewById<FrameLayout>(R.id.frame_layout)
val cardView = itemView.findViewById<FrameLayout>(R.id.cardview)
cardView.apply {
isFocusable = true
isFocusableInTouchMode = true
onFocusChangeListener = View.OnFocusChangeListener { v, hasFocus ->
if (hasFocus) {
AbstractCardPresenter.animateScaleUp(cardView as View)
frameLayout.background = itemView.context.resources.getDrawable(R.drawable.card_border)
descriptionView.visibility = View.VISIBLE
} else {
AbstractCardPresenter.animateScaleDown(cardView as View)
frameLayout.background = null
descriptionView.visibility = View.GONE
}
}
}
itemView.onAttachStateChangeListener {
onViewAttachedToWindow {
if (adapterPosition == 0) {
cardView.requestFocus()
}
}
}
}
}
U need to get rid of NestedScrollView
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="#dimen/margin_start_tv_home"
android:background="#null"
android:clipToPadding="false"
android:orientation="horizontal"
android:padding="#dimen/margin_medium_big"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
tools:context=".android.screens.auth.SelectCarrierActivity"
tools:listitem="#layout/imagecardview_station" />
I found the offending bit of code!! I was trying to get focus on the first ViewHolder of the RecyclerView upon load. That was causing the problem. Just need to find another way to do it now! This bit of code right there:
itemView.onAttachStateChangeListener {
onViewAttachedToWindow {
if (adapterPosition == 0) {
cardView.requestFocus()
}
}
}
I am having following layout
<merge>
<LinearLayout
android:id="#+id/ll_main"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
/>
<LinearLayout
android:id="#+id/ll_sub"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
/>
</merge>
What I want to do is to show/hide the ll_sub layout on runtime through setVisibility() but it is not working.
When I am setting android:visibility="gone" (also I had checked with invisible) from the xml of ll_sub then it is not displayed on the screen and this time when I use setVisibility() to show this layout on runtime, it is displayed but when I try to hide this layout once it is displayed then it is not hiding.
EDIT
I am trying to show/hide this linear layout on click of a button.
LinearLayout ll;
Button minimize;
int visibility=0;
#Override
public void onCreate(Bundle savedInstanceState)
{
ll=(LinearLayout)findViewById(R.id.ll_sub);
minimize=(Button)findViewById(R.id.minimize);
minimize.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
if(visibility==0)
{
visibility=2;
}
else
{
visibility=0;
}
ll.setVisibility(visibility);
}
});
}
It looks like you're setting the wrong constants for changing view visibility.
GONE == 8
INVISIBLE == 4
VISIBLE == 0
However, you should never rely on the actual values that Android happened to designate to represent their constants. Instead use the the values defined in the View class: View.VISIBLE, View.INVISIBLE, and View.GONE.
// snip...
if(visibility == View.VISIBLE)
{
visibility = View.GONE;
}
else
{
visibility = View.VISIBLE;
}
ll.setVisibility(visibility);
And don't forget to call invalidate() on the view :)
You should use the Constants provided by View
View.INVISBLE, View.VISIBLE, View.GONE
and also invalidate your View