Issue
I am trying to write a first Android
app and I hit the following issue.
This is a loop handling some buttons:
for (i in 0..7) {
val btnID = resources.getIdentifier('N'.plus(i.toString()),"id",packageName)
val imageBtn = findViewById<ImageButton>(btnID)
imageBtn.setBackgroundColor(0x00)
imageBtn.setOnClickListener {
val result = Math.pow(2.toDouble(),i.toDouble()).toInt()
val textView = findViewById<TextView>(R.id.textView2).apply {//
text = result.toString()
}
}
// Here I want to put a sticker: "Hi" on top of the button (imageBtn).
.....
}
The code above works, and the buttons behave as I expect. Now I would like to stick a label on top of each button. How can I do that? I have already tried tens of ways, following sample code I found on the net, but nothing works.
Below is a graphic to illustrate what I mean more precisely.
Of course "Hi" cannot be part of the button image because I need to change it dynamically. It can later become "Ho", "He", "Pa", ... or whatever according to the state of the app.
Solution
Since I had to spend some time and this may well be useful to someone else, I put here my solution. It now works exactly as I want.
Here it is:
for (i in 0..7) {
val btnID = resources.getIdentifier('N'.plus(i.toString()),"id",packageName)
val imageBtn = findViewById<ImageButton>(btnID)
imageBtn.setBackgroundColor(0x00)
imageBtn.setOnClickListener {
val result = Math.pow(2.toDouble(),i.toDouble()).toInt()
val textView = findViewById<TextView>(R.id.textView2).apply {//
text = result.toString()
}
}
setSticker(i,btnID)
}
fun setSticker(n:Int,btn:Int) {
val label = TextView(this)
label.id = View.generateViewId()
label.text = "Hi"
label.setTextColor(Color.rgb(0xFF,0xFF,0xFF))
label.setTypeface(null, Typeface.BOLD)
label.setTextSize(TypedValue.COMPLEX_UNIT_PX, 17.dpToPixels(this))
label.elevation = 0.dpToPixels(this) // To make the label visible (i.e. on top)
constraintLayout?.addView(label)
val constrSet = ConstraintSet()
constrSet.clone(constraintLayout)
constrSet.connect(label.id, ConstraintSet.LEFT, btn, ConstraintSet.LEFT)
constrSet.connect(label.id, ConstraintSet.RIGHT, btn, ConstraintSet.RIGHT)
constrSet.connect(label.id, ConstraintSet.TOP, btn, ConstraintSet.TOP)
constrSet.connect(label.id, ConstraintSet.BOTTOM, btn, ConstraintSet.BOTTOM)
constrSet.applyTo(constraintLayout)
}
Answered By - Michel
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.