要实现Android切换按钮保存状态自定义列表视图,可以按照以下步骤进行操作:
public class Item {
private String content;
private boolean isSwitchOn;
public Item(String content, boolean isSwitchOn) {
this.content = content;
this.isSwitchOn = isSwitchOn;
}
// Getter and Setter methods
}
public class CustomListAdapter extends BaseAdapter {
private Context context;
private List- itemList;
public CustomListAdapter(Context context, List
- itemList) {
this.context = context;
this.itemList = itemList;
}
@Override
public int getCount() {
return itemList.size();
}
@Override
public Object getItem(int position) {
return itemList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.item_layout, parent, false);
}
TextView textViewContent = convertView.findViewById(R.id.textViewContent);
final Switch switchButton = convertView.findViewById(R.id.switchButton);
final Item item = itemList.get(position);
textViewContent.setText(item.getContent());
switchButton.setChecked(item.isSwitchOn());
switchButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
item.setSwitchOn(isChecked);
}
});
return convertView;
}
}
public class MainActivity extends AppCompatActivity {
private List- itemList;
private CustomListAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = findViewById(R.id.listView);
itemList = new ArrayList<>();
itemList.add(new Item("Item 1", false));
itemList.add(new Item("Item 2", true));
itemList.add(new Item("Item 3", false));
adapter = new CustomListAdapter(this, itemList);
listView.setAdapter(adapter);
}
}
以上就是实现Android切换按钮保存状态自定义列表视图的解决方法,通过定义数据模型类、创建自定义列表项布局、编写自定义列表适配器并在Activity中使用适配器来完成相关功能。