mitai
mitai

Reputation: 314

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!

Upvotes: 2

Views: 3212

Answers (3)

alvessss
alvessss

Reputation: 1

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;
     }
}

Upvotes: 0

sha256
sha256

Reputation: 3099

Yes, there is.

int layoutId = getContext().getResources().getIdentifier("mylayoutid","layout", getContext().getPackageName());
if (layoutId == 0){
  // this layout doesn't exist
} else {
  setContentView(layoutId);
}

Upvotes: 6

pshegger
pshegger

Reputation: 2596

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

Upvotes: 0

Related Questions