Find button by ID in Kotlin - android

I have a user interface with multiple buttons. They have the IDs "button1", "button2", ...
I want to set an OnClickListener for all of them in a for loop. I dont want to type a line like button1.setOnClickListener for every button.
I have found one solution that works in java here: Android: Using findViewById() with a string / in a loop
And I tried to adapt it in Kotlin.
var buttons = ArrayList<Button>()
for (i in 1..7) {
var idString = "Button%i"
var buttonID = getResources().getIdentifier(idString, "id", packageName)
buttons.add( findViewWithTag(buttonID))
buttons[i].setOnClickListener(buttonclicked)
}
This throws an "Unresolved Reference" error. How can I access all buttons without typing a line for each of them?
Thanks in advance to all of you.

You call findViewWithTag() instead of findViewById() in your code.
Also you are not doing string interpolation correctly by var idString = "Button%i".
Change to this:
val buttons = ArrayList<Button>()
for (i in 1..7) {
val idString = "Button$i"
val buttonID = resources.getIdentifier(idString, "id", packageName)
buttons.add(findViewById(buttonID))
buttons[i].setOnClickListener(buttonclicked)
}

Related

Intent.getStringExtra() returns null in Kotlin Android

I don't know what mistake I am doing why it is returning null, I have seen other people problems I am not getting what I need exactly. I am sending the string data in this activity
val inspenctionIntent = Intent(this, InspectActivity::class.java)
inspenctionIntent.putExtra("Particulars", estimateItem.Particulars)
inspenctionIntent.putExtra("SSRItemNO", estimateItem.SSRItemNO)
inspenctionIntent.putExtra("Quantity", estimateItem.Quantity)
inspenctionIntent.putExtra("QuantityUnit", estimateItem.QuantityUnit)
inspenctionIntent.putExtra("Times", estimateItem.Times)
inspenctionIntent.putExtra("Rates", estimateItem.Rates)
inspenctionIntent.putExtra("RatesPer", estimateItem.RatesPer)
inspenctionIntent.putExtra("Total", estimateItem.Total)
startActivity(Intent(this#CheckMeasurementActivity, InspectActivity::class.java))
and trying to get that string extra in another activity but is returning null?
val Particulars = intent.getStringExtra("Particulars")
val SSRItemNO = intent.getStringExtra("SSRItemNO")
val Quantity = intent.getStringExtra("Quantity")
val QuantityUnit = intent.getStringExtra("QuantityUnit")
val Times = intent.getStringExtra("Times")
val Rates = intent.getStringExtra("Rates")
val RatesPer = intent.getStringExtra("RatesPer")
val Total = intent.getStringExtra("Total")
I tried by replacing var also still it is returning null?
Your error is this line.
startActivity(Intent(this#CheckMeasurementActivity, InspectActivity::class.java))
You declare inspenctionIntent but never use it, so others activity will get nothing since your intent send nothing to it.
So you need to change
startActivity(Intent(this#CheckMeasurementActivity, InspectActivity::class.java))
to
startActivity(inspenctionIntent)
You are started wrong intent so should use inspenctionIntent inside startActivity()
val inspenctionIntent = Intent(this, InspectActivity::class.java)
inspenctionIntent.putExtra("Particulars", estimateItem.Particulars)
inspenctionIntent.putExtra("SSRItemNO", estimateItem.SSRItemNO)
inspenctionIntent.putExtra("Quantity", estimateItem.Quantity)
inspenctionIntent.putExtra("QuantityUnit", estimateItem.QuantityUnit)
inspenctionIntent.putExtra("Times", estimateItem.Times)
inspenctionIntent.putExtra("Rates", estimateItem.Rates)
inspenctionIntent.putExtra("RatesPer", estimateItem.RatesPer)
inspenctionIntent.putExtra("Total", estimateItem.Total)
startActivity(inspenctionIntent)
You should write
Intent.putExtra("Particulars", estimateItem.Particulars)
Instead of
inspenctionIntent.putExtra("Particulars", estimateItem.Particulars)
and for others is the same.
Just change this-:
startActivity(Intent(this#CheckMeasurementActivity, InspectActivity::class.java))
to-:
startActivity(inspenctionIntent)
in last line of your code...

How to set the text of a Button using getResources() in Kotlin?

I'm trying to identify a button using getResources() and getIdentifier(), then set the text for it. The below code shows how I thought it should work (simply setting the ID and setting the text for the object).
while (c < 65) {
val resID = getResources().getIdentifier("S1", "id", getPackageName())
resID.text = ""
}
Instead I get an error, with ".text" showing red. How should I go about setting this up to run how I expected.
resID is the integer id of a Button "named" S1.
Use it to find the Button:
val resID = resources.getIdentifier("S1", "id", getPackageName())
val button = findViewById<Button>(resID)
button.text = ""
based on Docs getIdentifier returns Int , so you need findViewById and use the getIdentifier result in order to use the object
Kotlin Extensions do not work if the referenced int is not coming from R.id.
Button is a view, then you can access to it by using
findViewById<Button>(buttonId)
If you want to retrieve id from resources, just getResources().getIdentifier("S1", "id", getPackageName())
In conclusion, you see how this is going to be:
val buttonId = getResources().getIdentifier("S1", "id", getPackageName())
val button = findViewById<Button>(buttonId)
button.setText("")

Get the text of a dynamically created textfield in android studio (Kotlin)

So I'm trying to figure out how I would get the text from a dynamically created EditText field.
This is the code for the dynamic Text fields
private fun AddToDoItem() {
val EditText = EditText(this)
EditText.gravity = Gravity.TOP
EditText.gravity = Gravity.CENTER
EditText.tag = "ExtraField" + i
LinearLayout?.addView(EditText)
i++
}
And this is the code where I want to get the Textfields text
Finish.setOnClickListener {
var x = 0
val userId = mAuth.currentUser!!.uid
val mcDatabase = FirebaseDatabase.getInstance().getReference()
mcDatabase.child("Users").child(userId).child(ToDoName.text.toString()).push()
while (x < i) {
val currentUserDb = mDatabaseReference!!.child(userId).child(ToDoName.text.toString())
currentUserDb.child(i.toString()).setValue("ExtraField" + x.text) //HERE IS WHERE I WANT TO SET THE TEXT
x++
Toast.makeText(this, "Finished.", Toast.LENGTH_LONG).show()
}
}
Where its commented like "//HERE IS WHERE I WANT TO SET THE TEXT" is where I want the .text string.
(It's in the while loop)
There are two ways to handle this:
You are adding the EditText's to a LinearLayout therefore you can iterate over its children - as described here and therefore replacing the while loop.
The second way would be to add the EditText's to a List<EditText> and iterate over it, replacing the while loop.
The first solution would probably be cleaner, but both of them work in a very similar fashion.
Hope this helps you!

Programatically make an imageView visible/invisible using a variable

I have a Kotlin function, that works as expected when an imageView is explicitly called. However when a variable 'cellName' is used the code will not compile.
My objective here is to programatically generate the imageView name and then set/unset its visibility. Could someone please tell me where I am going wrong.
TIA
fun game(view: View) {
var col = 1
var row = 0
var cellName = ""
object : CountDownTimer(10000, 1000){
override fun onFinish() {
Toast.makeText(applicationContext, "Time's Up", Toast.LENGTH_LONG).show()
textView9.text = "Time: 0"
}
override fun onTick(p0: Long) {
textView9.text = "Time: "+ p0 /1000
// Hide current position
cellName = "imageView"+row+col
imageView01.setVisibility(View.INVISIBLE)
// Get next random position
// Show new Position
}
}.start()
}
So:
imageView01.setVisibility(View.INVISIBLE) --> works
cellName.setVisibility(View.INVISIBLE) -- does not compile
You can generate a view id (aka an R.id constant) by using Resources.getIdentifier().
A sample for your code (assuming you're running inside an Activity) might be:
int row = 0;
int col = 1;
String name = "imageView" + row + col;
int id = getResources().getIdentifier(name, "id", getPackageName());
ImageView imageView = findViewById(id);
imageView.setVisibility(View.INVISIBLE);
Sorry that this is in Java, not Kotlin. Hopefully you can adapt it.
Your best bet might be to just put all the ImageViews in question into a map where the value you have for "cellName" is the key. Then just retrieve each ImageView from the map.

Is Android java getResource.getIdentfier exist in IOS Swift?

My application has so many data. So There are so many textfield. Therefore I want to manage textView in iOS swift in the same way.
area1Layer = new TextView[25];
for(int k = 0; k < layer1; k++){// 층수 SET
area1Layer[k] = (TextView)findViewById(getResources().getIdentifier("layer"+(k+1),"id","kr.soen.areacard"));
area1Layer[k].setText(Integer.toString(k + 1) + "0" +ho1);
}
I assume that you want to identify the respective UITextField/UITextView seperately. This can be done by assigning different tags to the respective textfields/textviews.
let textField1: UITextField = UITextField()
textField1.tag = 1
let textField2: UITextField = UITextField()
textField2.tag = 2
and in the UITextFieldDelegate method,
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
if textField.tag == 1 {
//Type your code here
}
if textField.tag == 2 {
//Type your code here
}
}
Also you could assign outlets to each textfield/textview, and use the outlets to check.
#IBOutlet weak var textField1: UITextField!
#IBOutlet weak var textField2: UITextField!
and in the UITextFieldDelegate method,
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
if textField == textField1 {
//Type your code here
}
if textField == textField2 {
//Type your code here
}
}
The same can be done in the case of UITextView as well.
I believe that you want to identify each UITextField or UITextView separately and accordingly manipulate them. You can do it in the following way:
let textView1: UITextView = UITextView()
textView1.tag = 1
let textView2: UITextView = UITextView()
textView2.tag = 2
self.view.addSubview(textView1)
self.view.addSubview(textView2)
For identifying between different view objects, you can use .tag property in iOS by setting .tag in the above way.
To get different UITextView added to the self.view as a subView in swift, you can do the following:
if let textViewObject: AnyObject = self.view.viewWithTag(2) {
// first check is to identify if there is a given view with the tag
if let textView: UITextView = textViewObject as? UITextView {
}
}
The main difference is iOS uses an number based tag while Android uses a text key. You can accomplish the same thing with both. In iOS store all your labels in a collection and modify per tag. The collection type and syntax specifics for setting the tag depend on the way you wright your views.
After setting the tag via interface builder or view.tag = myTag; you can do something like:
for (int x=0; x<strings.count; x++){
UITextView *view = [self.view viewWithTag:x];
view.text = strings[x];
}

Categories

Resources