如何使用Butter Knife为ListView Android的页眉和页脚

时间:2018-03-02 04:07:35

标签: java android butterknife

我在列表视图中添加了一个页眉和页脚,如下所示:

lv = (ListView) findViewById(R.id.lv_process_person)
            View header = getLayoutInflater().inflate(R.layout.activity_input_forward_department_header, null);
            View footer = getLayoutInflater().inflate(R.layout.activity_input_forward_department_footer, null);
            lv.addHeaderView(header);
            lv.addFooterView(footer);

我在头文件中使用view如下:

btnForward = (TextView) header.findViewById(R.id.button_forward);
    btnForward.setText("SetText");

如何使用ButterKnife Liblary这些代码?我研究但没有恢复。谢谢你,对不起我的英语。

2 个答案:

答案 0 :(得分:1)

您可以使用ButterKnife文档中与此示例类似的内容:

  

您还可以通过提供自己的视图根来对任意对象执行绑定。

public class FancyFragment extends Fragment {
  @BindView(R.id.button1) Button button1;
  @BindView(R.id.button2) Button button2;

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fancy_fragment, container, false);
    ButterKnife.bind(this, view);
    // TODO Use fields...
    return view;
  }
}

作为ButterKnife.bind()的第一个参数传递的类必须包含使用@BindView注释的字段。最直接的方法是创建一个名为View的自定义ListViewHeader类或更具体的用途。

答案 1 :(得分:1)

这是我的代码的一部分。将视图持有者模式与静态内部类一起使用。

public class AudioOrderActivity extends AppCompatActivity {

    public static final String TAG = AudioOrderActivity.class.getSimpleName();
    @BindView(R2.id.ib_back)
    RelativeLayout ibBack;
    @BindView(R2.id.tv_title)
    TextView tvTitle;
    @BindView(R2.id.toolBar)
    RelativeLayout toolBar;
    private HeaderViews mHeaderViews;
    private FooterView mFooterViews;
    private View mHeader;
    private View mFooter;

    static class HeaderViews {
        ImageView ivPauseOrStart;
        @BindView(R2.id.iv_previous)
        ImageView ivPrevious;
        @BindView(R2.id.iv_next)
        ImageView ivNext;

        public HeaderViews(View view) {
            ButterKnife.bind(this, view);
        }
    }

    static class FooterView {
        @BindView(R2.id.tv_order_num)
        TextView tvOrderNum;
        @BindView(R2.id.tv_order_transaction_time)
        TextView tvOrderTransactionTime;

        public FooterView(View view) {
            ButterKnife.bind(this, view);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.shop_fragment_audioorder);
    }

    @Override
    protected void init() {
        mHeader = LayoutInflater.from(mContext).inflate(R.layout.shop_layout_head_audio_order_recycler, null);
        mFooter = LayoutInflater.from(mContext).inflate(R.layout.shop_layout_order_detail, null);
        mHeaderViews = new HeaderViews(mHeader);
        mFooterViews = new FooterView(mFooter);
        ButterKnife.bind(headerViews, header);
        ButterKnife.bind(footerViews, footer);
    }