我目前正在学习butterknife,我需要在我的客户适配器生成的不同视图上绑定特定的@OnClicks。我该怎么做呢?
我在其中一个问题中看到了答案,说他使用了@ onclick'在ViewHolder'内。我不确定如何完全实现这一点。有什么想法吗?
谢谢!
答案 0 :(得分:6)
想象一下,你有一个像这样的ViewHolder。
static class ViewHolder {
@InjectView(R.id.user_name)
TextView userName;
@InjectView(R.id.user_title)
TextView userTitle;
public ViewHolder(View view) {
ButterKnife.inject(this, view);
}
}
您可以为适配器中的每个视图绑定适配器getView方法中的事件。
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView != null) {
holder = (ViewHolder) convertView.getTag();
} else {
convertView = LayoutInflater.from(mContext).inflate(
R.layout.your_row_layout, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
holder.userName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Your stuff here
}
});
holder.userTitle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Your stuff here
}
});
return convertView;
}
答案 1 :(得分:3)
正如@Ugur建议您使用butterknife启动ViewHolder。您可以通过将此作为userName视图的示例添加到视图的单击侦听器:
@OnClick(R.id.user_name)
public void clickedUserName(SocialEyeTextView userName)
{
//Do something with user name
}
答案 2 :(得分:1)
我有ViewHolder
..
public class ViewHolder extends RecyclerView.ViewHolder {
@Bind(R.id.item_tipo_evento_estado_text) TextView text;
@Bind(R.id.item_text_radiobutton_check) AppCompatCheckBox checkBox;
public ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
@OnClick(R.id.btnCheck)
public void onCheck() {
Log.d("ViewHolder", "position ->" + getAdapterPosition());
}
}
确定我的R.id.btnCheck
是我的LinearLayout
内容所有Views
答案 3 :(得分:0)
在ViewHolder
class
static class ViewHolder {
public int getPosition;
@Nullable
@Bind(R.id.txt_title_name)
TextView txtTitle;
public ViewHolder(View view) {
ButterKnife.bind(this, view);
}
@OnClick(R.id.btn_download)
public void onCheck() {
Log.d("ViewHolder", "position ->" + getPosition);
}
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
holder.getPosition = position;
}