在许多问题中,人们说“在onCreateViewHolder中调用OnClickListener。你不需要在onBindViewHolder上调用OnClickListener每个项目”
@Override
public Viewholder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(itemLayout, parent, false);
final ViewHolder holder = new ViewHolder(v);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "position = " + holder.getAdapterPosition());
}
});
return new Viewholder(v);
}
@Override
public void onBindViewHolder(final BoardListViewHolder holder, int position) {
}
但在Logcat中,始终显示“position = -1”
这不正确。
为什么我应该在onCreateViewHolder中调用onClickListener?
答案 0 :(得分:3)
onCreateViewHolder中的getAdapterPosition始终为“-1”
您应该 return holder
而不是 new Viewholder(v)
。
代码结构
@Override
public Viewholder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(itemLayout, parent, false);
final ViewHolder holder = new ViewHolder(v);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "position = " + holder.getAdapterPosition());
}
});
return holder;
}
@Override
public void onBindViewHolder(final BoardListViewHolder holder, int position) {
}
答案 1 :(得分:2)
因为您正在返回新的ViewHolder
而不是您设置点击侦听器的那个。
而不是return new Viewholder(v)
,您应该return holder;
设置点击侦听器的更清晰的方法可以是
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(
R.layout.layout_item, parent, false));
}
public class ViewHolder extends RecyclerView.ViewHolder {
private ImageView image;
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// do what you need to do. getAdapterPosition() is useful here
}
});
}
}
答案 2 :(得分:1)
onCreateViewHolder
仅用于扩充布局资源,您不应在此处放置与持有者项目相关的任何方法。
相反,您必须使用onBindViewHolder
获取holder.getAdapterPosition
的值或设置onClickListeners
等。
答案 3 :(得分:0)
首先return new Viewholder(v)
代替OnClickListener
您可以在ViewHolder
中拥有getAdapterPosition()
,并按class ViewHolder extends RecyclerView.ViewHolder{
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "position = " + getAdapterPosition());
//do your stuff here
}
});
}
}
package de.gdv.sp.configuration;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.captcha.botdetect.web.servlet.CaptchaServlet;
@Configuration
public class CaptchaConfiguration extends WebApplicationInitializer {
@Bean(name = "captchaServlet")
public ServletRegistrationBean captchaServlet() {
return new ServletRegistrationBean(new CaptchaServlet(), "/kontakt");
}
}