Reputation: 4808
I am trying to implement a listview with toggle buttons. All thing is going well, the issue is with toggle button's method setChecked
. The button is automatically set to off set by itself, on going down to the list view. I am using a custom adapter and here is the getView
method:
public View getView(final int position, View convertView, ViewGroup parent) {
final Holder holder = new Holder();
View rowView = inflater.inflate(R.layout.list_view_layout,null);
holder.tv = (TextView) rowView.findViewById(R.id.tv_item);
holder.tb = (ToggleButton) rowView.findViewById(R.id.tgl_status);
holder.tv.setText(Name.get(position));
holder.tb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// The toggle is enabled
holder.tb.setChecked(isChecked);
Toast.makeText(activity, Name.get(position) + "ON", Toast.LENGTH_LONG).show();
} else {
// The toggle is disabled
Toast.makeText(activity, "OFF", Toast.LENGTH_LONG).show();
holder.tb.setChecked(isChecked);
}
}
});
rowView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(activity, "You Clicked "+Name.get(position), Toast.LENGTH_LONG).show();
}
});
return rowView;
}
Issue is with :
holder.tb.setChecked(isChecked);
It is always false.
My list_view_layout.xml
file is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_height="wrap_content">
<TextView
android:id="@+id/tv_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<ToggleButton
android:id="@+id/tgl_status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
I am using a fragment which uses this custom adapter.
Upvotes: 1
Views: 4932
Reputation: 1410
I don't see a problem here.
You're checking/unchecking this ToggleButton
IN the CheckedChangeListener
. That is: when you check this ToggleButton
, your onCheckedChange
will check it again. You're duplicating a not needed action.
If you're actually trying to check it according to a object (Let's say Weather
) in your ArrayList
of Weathers
inside your Adapter
, then you should go for:
if (weatherList.get(position).isChecked) {
holder.tb.setChecked(true);
} else {
holder.tb.setChecked(false);
}
Upvotes: 3