Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ButterKnife inside adapter

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?

like image 760
Stepan Avatar asked Nov 30 '16 13:11

Stepan


People also ask

What is the use of ButterKnife in Android?

Butterknife is a light weight library to inject views into Android components. It uses annotation processing. The @BindView annotation allow to inject views and performs the cast to the correct type for you.


2 Answers

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 to your Views.

like image 133
omerkaraca Avatar answered Oct 21 '22 12:10

omerkaraca


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

like image 44
EricDS Avatar answered Oct 21 '22 12:10

EricDS