Reputation: 25141
am very much a newbie when it comes to android development so bear with me. Im currently using Windows 8 / Eclipse.
My issue is, the findViewById
function seems to have gone mad, although I could very well be using it wrongly.
The app was working fine, then I 'dropped' a few new TextView
s on the page which seems to totally confuse it.
The findViewById
function now either finds the wrong control completely, or doesnt find anything at all (and will return null). I've checked my activity_main.xml
file and the id's are still correct.
Can anyone help?
This is a typical example of my usage:
public void toggleButtonNetwork_Click(View v) {
ToggleButton tb = (ToggleButton) this.findViewById(R.id.toggleButtonNetwork);//did work, now does not work!
}
The only insight I may add is that my R.java file looked like this when it was working:
...
public static final class id {
public static final int menu_settings=0x7f070004;
public static final int textViewGPS=0x7f070003;
public static final int textViewNetwork=0x7f070001;
public static final int toggleButtonGPS=0x7f070002;
public static final int toggleButtonNetwork=0x7f070000;
}
...
and now looks like this (broken):
public static final class id {
public static final int menu_settings=0x7f070006;
public static final int textView1=0x7f070004;
public static final int textView2=0x7f070005;
public static final int textViewGPS=0x7f070002;
public static final int textViewNetwork=0x7f070003;
public static final int toggleButtonGPS=0x7f070000;
public static final int toggleButtonNetwork=0x7f070001;
}
Upvotes: 3
Views: 1398
Reputation: 14472
This doesn't answer your question. I suspect that A--Cs comment is correct.
But, there is nothing to be confused about. findViewById
is really simple.
When you compile your app, the compiler generates R.java and adds a line for each view in your layout XMLs (and strings, drawables, colours etc - anything that is a "resource") and gives it a unique ID.
public static final int toggleButtonNetwork=0x7f070001;
The ID will change as you change your resources, but it doesn't matter. When you use findViewById
, you give it the "friendly name", in this case R.id.toggleButtonNetwork
, which is compiled into 0x7f070001
since public static final int toggleButtonNetwork
is a static constant.
When you inflate your view from XML, typically with setContentView, the view hierarchy of objects is built. The id of each object is the id found in R.java.
findViewById
returns a reference to the object, of type View
, which you then cast to whatever type of View it is which is why you use
= (Button)findViewById(R.id.toggleButtonNetwork);
Upvotes: 1
Reputation: 7394
Everthing is fine.
Always Just go to project -> clean And than run . Thats it.
Upvotes: 3
Reputation: 23655
This is a quite common problem. Try and invoke the Project/Clean...
on your project. It sometimes happens that the automatic generating of the R
classes goes wrong and this will force them to be rebuilt.
Upvotes: 5