[Java]Android automatic view initialization

04/14/2016 21:27 .SkyneT.#1
Do you hate typing
Code:
button = (Button)findviewbyid(R.id.button)
over and over again?

In this case this snippet should be very helpful:
It will initialize every instance of a View (buttons, textview,...) in an Activity automatically.
Code:
//For this to work, the member variables have to have the same name as in the layout file.

//example:
//MainActivity.java - button1
//activity_main.xml - android:id="button1"

Field[] fields = this.getClass().getDeclaredFields();
for(Field f : fields)
{
    if(View.class.isAssignableFrom(f.getType()))
    {
        int id = getResources().getIdentifier(f.getName(), "id", getPackageName());
        View v = findViewById(id);
        try
        {
            f.set(this, v);
        }catch (Exception ex)
        {
            Log.e("ERROR", "Couldn't set " + f.getName());
            ex.printStackTrace();
        }
    }
}
[Only registered and activated users can see links. Click Here To Register...]