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