How to use ButterKnife inside adapter

时光总嘲笑我的痴心妄想 提交于 2019-12-04 17:33:44

问题


I would like to use ButterKnife to bind my views inside listView adpater.

I tried this, but i can not simply use my "spinner" var.

public class WarmSpinnerAdapter extends ArrayAdapter<Warm> {

    Context context;

    public WarmSpinnerAdapter(Context context, int resource, Warm[] objects) {
        super(context, resource, objects);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = LayoutInflater.from(context).inflate(R.layout.item_spinner, null);


        return v;
    }

    @OnClick(R.id.spinner)
    public void onClick() {
        //open dialog and select
    }

    static class ViewHolder {

        @BindView(R.id.spinner)
        MyTextView spinner;

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

Any ideas please?


回答1:


You should pass your view to ButterKnife to bind it first.

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View v = LayoutInflater.from(context).inflate(R.layout.item_spinner, null);
    ButterKnife.bind(this,v);

    return v;
}

Then you will have access your Views.




回答2:


ButterKnife is binding your view to the ViewHolder class, so WarmSpinnerAdapter won't be able to access it directly. Instead, you should move this part inside the ViewHolder class:

@OnClick(R.id.spinner)
public void onClick() {
    //open dialog and select
}

From there, you could either call an internal method from the adapter or execute the logic directly inside the ViewHolder




回答3:


Since you're using an ArrayAdapter you need to have the proper ViewHolder logic in your getView() method. (You're onClick annotation is also not set correctly as it should be placed inside the ViewHolder class.)

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder viewHolder;
    if (convertView == null) {
        convertView = LayoutInflater.from(context).inflate(R.layout.item_spinner, null);
        viewHolder = new ViewHolder(convertView);
        convertView.setTag(viewHolder);
    } else {
        viewHolder = (ViewHolder) convertView.getTag();
    }

    // now you can access your spinner var.
    MyTextView spinner = viewHolder.spinner;

    return convertView;
}


来源:https://stackoverflow.com/questions/40890185/how-to-use-butterknife-inside-adapter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!