Reputation: 923
I have asked this question to almost everybody and got same answer.
Question : I designed a custom adapter because my ListView rows have a checkbox and a TextView. getView() method has a setOnClickListener() method and when I click the checkbox on application, is getView() method is invoked with setOnClickListener() or only setOnClickListener() executed ?
Answer : Only setOnClickListener() is executed.
New Question : If it is so, when clicking the checkbox in third row of the ListView, How is pos
variable set to 2(It already must be 2 because index of third row is 2 but what assigns 2 into pos
) ?
public View getView( int position, View convertView, ViewGroup parent ){
View rowView = myInflater.inflate( R.layout.model_row, null );
final int pos = position;
TextView textView = (TextView) rowView.findViewById( R.id.text );
final CheckBox checkBox = (CheckBox) rowView.findViewById( R.id.checkbox );
textView.setText( myList.get(position).getContent() );
checkBox.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
if( checkBox.isChecked() ){
myList.get( pos ).setChecking( checkControl.Checked );
}
else{
myList.get( pos ).setChecking( checkControl.NonChecked );
}
}
});
return rowView;
}
Upvotes: 2
Views: 298
Reputation: 13850
The View.OnClickListener
is an anonymous inner class in your code. In Java, if the anonymous class access any variables in the outside class, those values are copied into the anonymous class automatically via the autogenerated constructor, when you create the instance of the anonymous class.
In your code, the OnClickListener
is accessing the pos
integer. You are assigning the position
of the view to the integer pos
, and since the OnClickListener
is accessing that integer, it is copied into the OnClickListener
anonymous class.
Upvotes: 2