Home > database >  to create variables, loops in kotlin?
to create variables, loops in kotlin?

Time:01-20

I create app for Android on Kotlin,I need to create 55 variables to work with them in code,how to do it using a for loop? Variables should be look like this: val EditText0: EditText = findViewById(R. id.et0) val EditText1: EditText = findViewById(R. id.et1) and so on

CodePudding user response:

You should use getIdentifier()

for(int i=0; i<some_value; i  ) {
   for(int j=0; j<some_other_value; j  ) {
    String buttonID = "btn"   i   "-"   j;
    int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
    buttons[i][j] = ((Button) findViewById(resID));
    buttons[i][j].setOnClickListener(this);
   }
}

This is Java but same logic for kotlin.

CodePudding user response:

When you have many of a similar kind of variable like this, you really should have a single List variable for all of them.

If they have consistent names like this, you can generate the IDs using resources.getIdentifier. It's easier using a List constructor than a for loop.

// In an Activity:
val myEditTexts: List<EditText> = List(55) { index ->
    val id = resources.getIdentifier("et$index", "id", packageName)
    findViewById<EditText>(id)
}

// In a Fragment's onViewCreated function:
val myEditTexts: List<EditText> = with(requireContext()) {
    List(55) { index ->
        val id = resources.getIdentifier("et$index", "id", packageName)
        view.findViewById<EditText>(id)
    }
}

If you don't want to keep all of them in a single list, then you should use View Binding to let the properties be generated for you.

  •  Tags:  
  • Related