Here is my custom arrayadapter class, I want to change the image resource of a button in each row when I click ont it, it works but an other button in an other row also changes. thanks for your help !
public class Coursadapter extends ArrayAdapter<String> {
Context context;
int layoutResourceId;
ArrayList<String> data = null;
WeatherHolder holder;
public Coursadapter(Context context, int layoutResourceId,
ArrayList<String> data) {
// super(context, layoutResourceId, data, coeff);
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, null);
holder = new WeatherHolder();
holder.name = (TextView) row.findViewById(R.id.item_cours_name);
holder.b = (ImageButton) row.findViewById(R.id.button);
holder.b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
WeatherHolder w = (WeatherHolder) v.getTag();
w.b.setImageResource(R.drawable.butgreen);
}
});
row.setTag(holder);
} else {
holder = (WeatherHolder) row.getTag();
}
holder.b.setTag(holder);
String name1 = data.get(position);
holder.name.setText(name1);
return row;
}
static class WeatherHolder {
TextView name;
ImageButton b;
}
}
You can declare variable int that will hold the position of selected item and
public void onItemClick(AdapterView<?> adapter, View arg1, int position, long id) {
mSelectedItem = position;
mAdapter.notifyDataSetChanged();
}
and in your custom adapter getView method check the position and change the image of your button
public View getView(int position, View convertView, ViewGroup parent) {
if (position == mSelectedItem) {
// set your image
}
Look i try this code with me and work , implements OnClickListener in your activity
public class MainActivity extends Activity implements OnClickListener
and in your getView method
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = ((Activity) context)
.getLayoutInflater();
row = inflater.inflate(layoutResourceId, null);
holder = new WeatherHolder();
holder.name = (TextView) row.findViewById(R.id.item_cours_name);
holder.b = (ImageButton) row.findViewById(R.id.button);
holder.b.setOnClickListener(MainActivity.this);
and the implement the Onclick method set the resource
@Override
public void onClick(View v) {
WeatherHolder w = (WeatherHolder) v.getTag();
w.b.setImageResource(android.R.drawable.star_big_on);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With