Can someone please try and explain this code for me, I don’t really understand any of it and nowhere on the web seems to explain it. I’ve brought a copy of ‘Android Development for Dummies’ and it hasn’t really helped me.
private TextView txtMineCount;
private TextView txtTimer;
txtMineCount = (TextView) findViewById(R.id.MineCount);
txtTimer = (TextView) findViewById(R.id.Timer);
// set font style for timer and mine count to LCD style
Typeface lcdFont = Typeface.createFromAsset(getAssets(),
"fonts/lcd2mono.ttf");
txtMineCount.setTypeface(lcdFont);
txtTimer.setTypeface(lcdFont);
Thanks in advance guys.
This declares two local variables that can hold references to a TextView. At first they do not point to anything…so you have to assign them.
Here we assign the two variables. We call a method of the framework to do a lookup among the text-based widgets that have been created by an ID. Importantly we’re not creating these widgets here. We are just finding the already-allocated object instances which correspond to some ID constants we use to name them.
It’s not necessarily “safe” to assume these lookups succeed in the general case, because View.findViewById() can return
null. But the person who wrote this code is assuming that there have indeed been TextView objects created elsewhere in the code which have those particular IDs.(If they’re wrong about that, then trying to set the typeface on
txtMineCountortxtTimerwill just cause an exception…)Android has some default fonts that ship with the system. But this program wants to make use of a TrueType Font File which has been embedded in the font subdirectory of the application’s assets (basically a bunch of files that travel along inside your application bundle). This creates a Typeface object suitable for applying to a TextView out of that file.
This simply sets the typeface used by the two TextViews to the font from above.
Note that you can get an equivalent effect without the intermediate variables. This code should do the same thing as what you posted:
But it’s harder to read this way, and by not saving intermediate results in variables you can end up computing that intermediate result multiple times. For instance, the
Typeface.createFromAssetcode is run twice with the same parameters when you write it this way.