nicole kidman nicole kidman - 5 months ago 21
Android Question

Android : Listview First button selected error

When listview Start i found First button was selected ?
i try make on click button event with listview but i don't know the reason ! how i can make it default like all buttons in list ?
take a look about image please.

android image button

@Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View row;
row = convertView;
final ContactHolder contactHolder;
if (row == null) {
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row, parent, false);
contactHolder = new ContactHolder();
contactHolder.tx_id = (TextView) row.findViewById(R.id.usersName2);
contactHolder.tx_id = (TextView) row.findViewById(R.id.usersName2);
contactHolder.loadId = (TextView) row.findViewById(R.id.loadMoreID);
contactHolder.tx_name = (TextView) row.findViewById(R.id.usersName);
contactHolder.image_tx = (ImageView) row.findViewById(R.id.usersPic);
contactHolder.sug_add = (Button) row.findViewById(R.id.sug_id);

row.setTag(contactHolder);


} else {
contactHolder = (ContactHolder) row.getTag();

}
final Contacts_Sug contacts = (Contacts_Sug) this.getItem(position);
contactHolder.image_tx.setImageResource(R.mipmap.ic_launcher);
contactHolder.tx_id.setText(contacts.getId());
contactHolder.tx_name.setText(contacts.getName());
imgLoader.DisplayImage(contacts.getImage(), contactHolder.image_tx);

contactHolder.tx_name.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
contacts.setSelectedPosition(position); //Set position here
contactHolder.sug_add.setText("Selected");
}


});
if(contacts.getSelectedPosition() == position){
contactHolder.sug_add.setText("Selected");
} else{
contactHolder.sug_add.setText("Follow");

}

return row;
}


public class ContactHolder {
TextView tx_id, tx_name,loadId;
ImageView image_tx;
public Button sug_add;

}

Answer

This is because by default, the value of selectedPosis "0".

Change your Contacts_Sug class to have the selectedPos member variable initialized to -1.

private int selectedPos = -1;
Comments