Hey this is my first time trying anything like so I don't know if this is even close to the best way to do this, but I thought it would work. I'm trying to go through the XML layout file and set all TextView
's to be INVISIBLE. When the following method is called I get a NullPointerException
public void numPlayerSetup(){
{
for(int i = 3; i <= 6; i++)
for(int z = 2; z <= 10; z++){
int resID = getResources().getIdentifier("TextView"+Integer.toString(z) + Integer.toString(i), "id", this.getPackageName());
if(resID != 0){
TextView text = (TextView) this.findViewById(resID);
text.setVisibility(View.INVISIBLE);
}
}
Let me know if you have any suggestions. Thanks!
Well, are the ids going to change? If not, just set up an int[] of TextView IDs, and loop through those, e.g.:
int[] ids = {
R.id.tv1, R.id.tv2, R.id.tv3 //...
}
for(int i : ids) {
TextView tv = (TextView)findViewById(i);
tv.setVisibility(View.INVISIBLE);
}
I would definitely not try using reflection, it'd be a lot less efficient than doing it in other ways. If you don't know the IDs of the TextViews ahead of time, why not try something like this (assuming your root layout is a RelativeLayout):
RelativeLayout root = (RelativeLayout)findViewById(R.id.root);
for(int i = 0; i < root.getChildCount(); i++) {
View v = findViewById(i);
if(v instanceof TextView) {
((TextView)v).setVisibility(View.INVISIBLE);
}
}
Since you've already accepted, I'll assume method 1 worked, because I just realized I was horribly off on method 2. It should be getChildAt(i)
, not findViewById(i)
, as that would just be calling findViewById(0|1|2|...etc)
. Below is a corrected version:
RelativeLayout root = (RelativeLayout)findViewById(R.id.root);
for(int i = 0; i < root.getChildCount(); i++) {
View v = root.getChildAt(i);
if(v instanceof TextView) {
((TextView)v).setVisibility(View.INVISIBLE);
}
}
I haven't tested that, but it sounds good in theory. :)