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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。