In Android layouts play a vital role in determining the performance and efficiency of the application.Although there exists the most commonly used mechanisms to access Android Layout effectively , In this tutorial we are going to look at the How to make use of Template Class for accessing the android layouts.

Accessing views from the layout in an activity

In Android activity’s (and fragment) source code ,you frequently need to access the views to access and modify their properties.

In an activity a developer can use the findViewById(id) method call to search for a view in the current layout. The id is the ID attribute of the view in the layout. The usage of this method is demonstrated by the following code.

@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView tV = (TextView) findViewById(R.id.mytextExample);

    // TODO do something with the TextView
}

It is also possible to search in a view hierarchy with the findViewById(id) method, as demonstrated in the following code snippet.

// search in the layout of the activity
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.mylayout);

// afterwards search in linearLayout for another view
TextView textView = (TextView) linearLayout.findViewById(R.id.mytext);

// note, you could have directly searched for R.id.mytext, the above coding
// is just for demonstration purposes




Template Class

You could also build a utility method which makes access to views easier.


public class ClsUiUtils {
   public static <T extends View> T findView(View root, int id)      {
      return (T) root.findViewById(id); }

   public static <T extends View> T findView(Activity activity, int id)      
    {
      return (T) activity.getWindow().getDecorView().getRootView().find ViewById(id); 
   }
}

This would allow you to find the view without explicit cast in your view hierarchy.

Button button = ClsUiUtils.findView(this, R.id.button);