美文网首页
Android 动态获取资源文件的id

Android 动态获取资源文件的id

作者: AR7_ | 来源:发表于2018-01-08 17:13 被阅读435次

    在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);
    
    

    相关文章

      网友评论

          本文标题:Android 动态获取资源文件的id

          本文链接:https://www.haomeiwen.com/subject/szbbnxtx.html