android动态资源文件,Android 动态获取资源文件的id

本文介绍了如何在Fragment中动态获取并使用图片ID,以及在RecyclerViewAdapter中根据类型动态加载不同布局的方法。通过设置有规律的字符串与资源ID结合,避免了冗余的if判断和重复的LayoutInflater代码,提高了代码的可读性和效率。
摘要由CSDN通过智能技术生成

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值