我的ListView每行都有多个项目。如何在custon ArrayAdapter类的getView()中为一个Item设置一个OnCLickListener,而不是ListView的整行?
@NonNull
@Override
public View getView(final int position, @Nullable final View convertView, @NonNull final ViewGroup parent) {
currentLayout = getItem(position);
myViewHolder= null;
view = convertView;
if (convertView == null) {
view = LayoutInflater.from(getContext()).inflate(R.layout.rowlayout, parent, false);
myViewHolder= new ViewHolder(view);
view.setTag(myViewHolder);
}
myViewHolder= (ViewHolder) view.getTag();
myViewHolder.content.setText(currentLayout.getContent());
myViewHolder.number.setText("1");
return view;
}
感谢您的回答。
答案 0 :(得分:1)
首先澄清一下,你膨胀的view
是行布局。要在子项上设置on click侦听器,只需按id查找该项,然后设置侦听器:
//It can be any type of view that supports on click listener
//Using TextView as an example
//Don't forget to assign an id to the child in xml
TextView childView = (TextView) view.findViewById(R.id.enter_child_id);
childView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Do something
}
});
要为不同的行设置不同的侦听器,最好在onBindViewHolder
而不是getView
中设置侦听器。 getView
仅用于扩充视图,因此会使所有行上的所有侦听器都无法区分。在这种情况下,您可以直接从viewholder
@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
TextView childView = holder.childView;
childView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Do something
}
});
}
答案 1 :(得分:0)
@NonNull
@Override
public View getView(final int position, @Nullable final View convertView, @NonNull final ViewGroup parent) {
currentLayout = getItem(position);
myViewHolder= null;
view = convertView;
if (convertView == null) {
view = LayoutInflater.from(getContext()).inflate(R.layout.rowlayout, parent, false);
myViewHolder= new ViewHolder(view);
view.setTag(myViewHolder);
}
myViewHolder= (ViewHolder) view.getTag();
myViewHolder.content.setText(currentLayout.getContent());
myViewHolder.number.setText("1");
yourview.setonclickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
do your stuff here
}
});
return view;
}