【发布时间】:2019-02-04 01:57:11
【问题描述】:
我有一个包含 2 个对象的列表视图项:1 个文本视图(字符串)和 1 个切换按钮(布尔值)。我正在使用自定义适配器和自定义 ArrayList 来显示这些项目,并且我想在每次按下来自不同活动的按钮时添加一个项目。问题是,当我按下按钮添加新的列表视图项目时,它会用新的而不是添加新行替换旧的。我尝试使用 myadapter.notifydatasetchanged() 更新列表视图,但没有奏效,因为当活动发生变化时,忘记了数组的大小,就像从头开始添加新行一样。
//Constructor
MyAdapter(Context context, List<Model> ModelArrayLista)
{
super(context,0,ModelArrayLista);
this.contexts = context;
this.ModelArrayList = ModelArrayLista;
}
@Override
public int getCount() {
return ModelArrayList.size();
}
public void remove(int position)
{
ModelArrayList.remove(position);
this.notifyDataSetChanged();
}
public View getView(int position, View convertView, @NonNull ViewGroup parent)
{
View listItem = convertView;
if(listItem == null)
{
listItem = LayoutInflater.from(contexts).inflate(R.layout.listview_item, parent, false);
}
Model currentModel = ModelArrayList.get(position);
TextView mtime = listItem.findViewById(R.id.textView1);
mtime.setText(currentModel.getTime());
final Switch mswitch = listItem.findViewById(R.id.switch1);
mswitch.setChecked(currentModel.getSwitch_btn());
final Intent disabled_intent = new Intent(contexts, Clock_Activity.class);
final Intent enable_intent = new Intent(contexts,Clock_Activity.class);
// Switch button - Turn on/Turn off
mswitch.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
if(mswitch.isChecked())
{
enable_intent.putExtra("enable",en);
contexts.startActivity(enable_intent);
}
else
{
disabled_intent.putExtra("disable", dis);
contexts.startActivity(disabled_intent);
}
}
});
return listItem;
}
public class Model extends ArrayList<Model> {
private String time;
private boolean switch_btn;
public Model(String wra,Boolean switcher)
{
this.time = wra;
this.switch_btn = switcher;
}
public String getTime()
{
return time;
}
public boolean getSwitch_btn()
{
return switch_btn;
}
}
//OnCreate
Initialisations();
//get a String value that control our adapter
Intent intent = getIntent();
Bundle b = intent.getExtras();
if(b!= null)
{
get_time = b.getString("time");
}
int num = intent.getIntExtra("number", 0);
list = new ArrayList<>();
//call our custom adaptersS
myAdapter = new MyAdapter(this,list);
listView.setAdapter(myAdapter);
//get a boolean value that controls our adapter
showthelist = intent.getBooleanExtra("keyList",false);
if(showthelist)
{
list.add(new Model(get_time,true));
myAdapter.notifyDataSetChanged();
}
if(num == 1)
{
list.set(0,new Model(get_time,false));
}
【问题讨论】:
-
目前您没有在任何地方保存现有数据。您需要将现有行保存到磁盘(SQLite 数据库可以工作),或者保存在显示列表的活动之外的内存中。然后在每次加载活动时加载现有数据。您还需要将新行保存到数据库中。