ButterKnife在动态加载布局时出现无法bind问题

2017-04-07  本文已影响0人  FallBlank

场景还原

项目里有一段关于RecyclerView的代码,涉及到动态加载条目项,每个条目除了一小部分内容不同外,基本信息都是一样的。很自然的想到了通过继承来实现差异。<br />
父类:

public abstract class BaseHolder extends RecyclerView.ViewHolder {
    
    @BindView(R.id.container)
    FrameLayout mContainer;

    public BaseHolder(View itemView) {
        super(itemView);
        ButterKnife.bind(this, itemView);
    }
  /*省略所有setter方法*/
}

其中itemview中包含了所有条目都包含的相同基本内容和一个FrameLayout用来实现动态布局加载。<br />

子类:

public class SubHolder extends BaseHolder {

    @BindView(R.id.tv_content)
    TextView mContentView;

    public SubHolder(View itemView) {
        super(itemView);
        Context context = itemView.getContext();
        View root = LayoutInflater.from(context)
                .inflate(R.layout.item_sub_content,mContainer,true);
        //确定绑定情况
        assert null != mContentView;
    }

    public void setContent(String content){
        mContentView.setText(content);
    }
}

在SubHolder中View root就是个性化内容的部分。<br />
这段代码会在运行时抛出:

/*异常是我修改的,上面的代码只是说明问题*/
java.lang.IllegalStateException: Required view 'tv_content' with ID 2131558562 for field 'mContentView' was not found

问题分析

SubHolder构造方法调用super(itemview),进而调用Butterknife.bind(this,itemview),从而从父到子进行View注入,但是这时动态布局root还没有加载mContainer中,所以注入时findViewById()是找不到对于id,导致异常发生。<br />

解决办法

我既不想写单独写findViewById()sssss...(复数加s,/手动滑稽),也不想改变继承结构。<br />
分析现状面临的问题:

解决方案:

修改后的SubHolder:

public class SubHolder extends BaseHolder {

    @BindView(R.id.tv_content)
    @Nullable TextView mContentView;

    public SubHolder(View itemView) {
        super(itemView);
        Context context = itemView.getContext();
        View root = LayoutInflater.from(context)
                .inflate(R.layout.item_sub_content,mContainer,true);
       ButterKnife.bind(this,itemView);
    }

    public void setContent(String content){
        mContentView.setText(content);
    }
}

玉有瑕疵

基类中的view被调用了两次findViewById(),代价很高。

上一篇 下一篇

猜你喜欢

热点阅读