'Android - check if layout exists

Is there any way I can check if a certain layout ID exists before using it with setContentView(R.layout.mylayoutid)?

Something like:

if(layout_exists("mylayoutid"))
    setContentView(R.layout.mylayoutid);
else
    setContentView(R.layout.defaultlayout);

couldn't find anything in the developer docs.

Thanks!



Solution 1:[1]

As it is a static integer in the R.java file you can't compile your app, if it does not exist.

Solution 2:[2]

This function may helps

public static boolean checkLayout(Context context, int id)
{
     final View testView;
     try
     {
          testView = LayoutInflater.from(context)
              .inflate(id, null);

          return true;
     }
     catch (Resources.NotFoundException e)
     {
         e.printStackTrace();
         return false;
     }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 pshegger
Solution 2 alvessss