Android 动态获取资源文件的id

在Fragment中获取图片的id:

            String tv = "tv_tianqi_tomorrow";
            int tvId = getResources().getIdentifier(tv + (i - 1), "id", getContext().getPackageName());
            TextView tvDay = (TextView) getBaseRootView().findViewById(tvId);

在Fragment的RecyclerViewAdapter中,因为要加载不同类型的布局,所以想到了动态加载布局的id,一番探索,得出成果,通过设置type来区别,就不用if来判断重复写LayoutInflater的代码了,并且将布局的id设置成有规律性,如下所示,动态获取布局文件的id:

        //四个布局
        R.layout.fragment_homeforcunt_tomorrow
        R.layout.fragment_homeforcunt_week
        R.layout.fragment_homeforcunt_month
        R.layout.fragment_homeforcunt_year
        type的值为 0,1,2,3
        HomeAPI.ConstellationType是字符串数组,包含tomorrow,week,month,year.
        //正常写法
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_homeforcunt_tomorrow, parent, false);

        //简写
        String lay = "fragment_homeforcunt_";
        int layoutId = parent.getContext().getApplicationContext().getResources().getIdentifier(lay + (HomeAPI.ConstellationType[type]), "layout", parent.getContext().getApplicationContext().getPackageName());
        View view = LayoutInflater.from(parent.getContext()).inflate(layoutId , parent, false);

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容