How the item.setOnClickListener works (view - method ())

0

How does this item.setOnClickListener(view -> method()); work? I had never seen this type of call, I saw it today and I was curious about this view , where does it come from? How does this type of call work?

@Override
    public void onBindViewHolder(LineHolder holder, int position) {
        holder.title.setText(String.format(Locale.getDefault(), "%s, %d - %s",
                mUsers.get(position).getName(),
                mUsers.get(position).getAge(),
                mUsers.get(position).getCity()
        ));

        holder.moreButton.setOnClickListener(view -> updateItem(position));
        holder.deleteButton.setOnClickListener(view -> removerItem(position));
    }
    
asked by anonymous 20.04.2018 / 07:01

2 answers

2

The syntax in question is a lambda syntax introduced in Java 8, explained in detail in this answer .

Write this in Java 8:

holder.moreButton.setOnClickListener(view -> updateItem(position));

It's the equivalent of what was written like this in Java 7:

holder.moreButton.setOnClickListener(new View.OnClickListener() {
    @Override public void onClick(View v) {
        updateItem(position);
    }
});
    
20.04.2018 / 12:47
0

Structured ViewHolder class

/**
 * A classe ViewHolder internamente guarda a view
 */
public class LineHolder extends RecyclerView.ViewHolder {
    TextView title;
    Button moreButton,deleteButton;

    /**
     * contrutor onde a View é adicionada
     * E inflado os demais elementos da view
     * @param itemView
     */
    public LineHolder(View itemView) {
        super(itemView);

        title =  itemView.findViewById(R.id.title);
        morebutton =  itemView.findViewById(R.id.moreButton);
        deleteButton =  itemView.findViewById(R.id.deleteButton);

    }
}

Where Holder is created and inserted your view

/**
 * Aqui que a View do Holder é inflada
 */
public LineHolder onCreateViewHolder(ViewGroup parent, int type) {
    return new LineHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_line_holder, parent, false));
}

Then you upgrade the holder

/**
 * Como os Holders são views reaproveitadas, é necessario fazer sua atualização quando ele pe chamado, e este metodo é para fazer a atualização dos recursos da view
 * @param holder
 * @param position
 */
public void onBindViewHolder(LineHolder holder, int position) {
    holder.title.setText("some text");

    //chamda da função lambda: necessario java 8 para executar ela
    holder.moreButton.setOnClickListener(view -> updateItem(position));

    //chamada padrão
    holder.moreButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            updateItem(position);
        }
    });

    holder.deleteButton.setOnClickListener(view -> removerItem(position));
}
    
20.04.2018 / 14:48