Android - check if layout exists

后端 未结 2 951
时光说笑
时光说笑 2021-01-21 20:25

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(\"m         


        
相关标签:
2条回答
  • 2021-01-21 20:38

    Yes, there is.

    int layoutId = getContext().getResources().getIdentifier("mylayoutid","layout", getContext().getPackageName());
    if (layoutId == 0){
      // this layout doesn't exist
    } else {
      setContentView(layoutId);
    }
    
    0 讨论(0)
  • 2021-01-21 20:52

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

    0 讨论(0)
提交回复
热议问题