如何在代码中为动态加入LinearLayout的复用布局内TextView设置文本
问题原因
- 你当前调用
inflate(@LayoutRes int resource, @Nullable ViewGroup root)方法时,返回值是传入的第二个参数root也就是tempContainer本身,不是你刚加载的temp_layout根布局,所以你后续从这个view里找子控件自然找不到目标TextView。
修复方案
方案1:使用findViewById实现(无需改动现有配置)
修改循环内的加载逻辑如下:
val dayTime = listOf(DayTime.NIGHT, DayTime.MORNING, DayTime.DAY, DayTime.EVENING) val tempContainer = binding.tempContainer val inflater = LayoutInflater.from(requireContext()) for (temp in dayTime) { val weather = weatherData.getWeather(temp) // 先加载布局不添加到父容器,拿到子布局实例 val childView = inflater.inflate(R.layout.temp_layout, tempContainer, false) as LinearLayout // 为子布局设置权重,水平方向权重生效要把宽设为0 childView.layoutParams = LinearLayout.LayoutParams( 0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f ) // 查找子布局内的TextView赋值,替换为你实际要展示的内容 childView.findViewById<TextView>(R.id.txt_daytime).text = temp.name childView.findViewById<TextView>(R.id.txt_temp).text = weather.temp?:"-" // 把配置好的子布局添加到容器 tempContainer.addView(childView) }
方案2:使用ViewBinding实现(更安全,避免空指针和类型转换错误)
首先确保你的模块开启了ViewBinding,然后直接用复用布局生成的绑定类操作控件:
val dayTime = listOf(DayTime.NIGHT, DayTime.MORNING, DayTime.DAY, DayTime.EVENING) val tempContainer = binding.tempContainer for (temp in dayTime) { val weather = weatherData.getWeather(temp) // 生成复用布局的绑定实例,布局名为temp_layout时绑定类默认名为TempLayoutBinding val itemBinding = TempLayoutBinding.inflate(LayoutInflater.from(requireContext()), tempContainer, false) // 直接通过绑定类访问控件赋值 itemBinding.txtDaytime.text = temp.name itemBinding.txtTemp.text = weather.temp?:"-" // 设置布局权重 (itemBinding.root.layoutParams as LinearLayout.LayoutParams).weight = 1f // 添加到容器 tempContainer.addView(itemBinding.root) }
额外注意点
父容器tempContainer是水平方向的LinearLayout,子布局要让weight生效,必须把layout_width设为0dp,原布局里写的match_parent宽度在权重场景下会失效,上述方案已经做了对应适配。
内容的提问来源于stack exchange,提问作者SoulReaver313
相关产品推荐
相关产品推荐

