Reputation: 314
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
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
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
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