Android - 检查布局是否存在

mit*_*tai 2 android android-layout

在使用setContentView(R.layout.mylayoutid)之前,有什么方法可以检查某个布局ID是否存在?

就像是:

if(layout_exists("mylayoutid"))
    setContentView(R.layout.mylayoutid);
else
    setContentView(R.layout.defaultlayout);
Run Code Online (Sandbox Code Playgroud)

在开发人员文档中找不到任何内容.

谢谢!

sha*_*256 6

就在这里.

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