-3

This is the section of code:

int buttonXa = 0, buttonXb = 4, layoutNum = (buttonXb - 1);
String layoutXNum = String.valueOf(layoutNum);
String layoutX;
LinearLayout layoutXab;
do {
    layoutX = "ll" + layoutXNum;
    layoutXab = (LinearLayout)layoutX;
    buildButtons(layoutXab, buttonXa, buttonXb);
    buttonXa += 4;
    buttonXb += 4;
    layoutNum += 1;
} while (buttonXa < 12);

Why doesn't the casting work? What is the correct code?HI there @J.Knight and any others This code is trying to send to the "build buttons" function, a linear layout, whose name is built dynamically within a "do while" loop, the first time the layout is called ll3 then ll4 and so on...The name was built and put into a String variable, but now needs to be converted to a Linear Layout variable... Thanks Emuna

Emuna613
  • 15
  • 3
  • What is the "casting" that doesn't work? Please show complete code and error message. – Dat Nguyen Jun 13 '17 at 03:32
  • How does class hierarchy of those two have anything to do with each other, why would you want it to work? – Shadov Jun 13 '17 at 03:32
  • What exactly are you trying to accomplish? I can think of a few different things you might be trying to do here and reasons it can't be done this way but I would be wasting time by explaining each scenario. The casting is not the issue there, you have a bigger problem on your hands. – J. Knight Jun 13 '17 at 03:36
  • HI there @J.Knight and any others This code is trying to send to the "build buttons" function, a linear layout, whose name is built dynamically within a "do while" loop, the first time the layout is called ll3 then ll4 and so on...The name was built and put into a String variable, but now needs to be converted to a Linear Layout variable... Thanks Emuna – Emuna613 Jun 13 '17 at 03:52
  • Ahh ok, so this is not possible in Java. It might be worth reading this question. https://stackoverflow.com/questions/6729605/assigning-variables-with-dynamic-names-in-java – J. Knight Jun 13 '17 at 04:29
  • Thanks @J.Knight. – Emuna613 Jun 13 '17 at 04:42

2 Answers2

0

The variable layoutX is of type 'String'.
The variable layoutXab is of type 'LinearLayout'

A 'LinearLayout' is not a sub-type of 'String', nor is 'String' a sub-type of 'LinearLayout'.

Casting is a way of specialising or generalising a type, and neither of these two types are a specialisation of the other.

Gov
  • 375
  • 1
  • 9
0
//Get the ID for R.layout.button1 
int resID = context.getResources().getIdentifier("button1", "layout", context.getPackageName());
//context could be an object of Activity too

Remember that this way is slower than directly using the resource ids, especially when you have hundreds of such ids to convert from String to int.

For more on Resource refer to this link https://developer.android.com/reference/android/content/res/Resources.html

Hi Ten
  • 93
  • 2
  • 16