【发布时间】:2020-08-07 05:57:31
【问题描述】:
我正在尝试实现两个使用意图在它们之间交换信息的活动。 Activity#1 包含一个空的列表视图和一个在按下时启动 Activity#2 的按钮。在 Activity#2 上,我有一些文本框字段和一个“保存”按钮,通过 intent.putExtra 方法将信息发送到 Activity#1。 问题是每次我尝试使用 Activity#2 传递的信息创建新视图时,列表都会覆盖第一个元素。
您可以在下面看到 Activity#1 的 OnCreate 方法:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_explorer);
notesList = findViewById(R.id.listviewNotes);
FloatingActionButton myFab = this.findViewById(R.id.fabAddNote);
myFab.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intentNoteEditor = new Intent(getApplicationContext(), NoteEditor.class);
startActivity(intentNoteEditor);
//Log.i("Lista",notesList.getCount()+"");
}
});
Intent intent =getIntent();
Bundle extras =intent.getExtras();
if(extras!=null){
if(extras.containsKey("isnewNote")){
isnewElement=extras.getBoolean("isnewNote",false);
}
}
if(isnewElement==true){
//***************Fetch data from intent***************//
notetext = intent.getStringExtra("noteText");
notecolor = intent.getStringExtra("noteColor");
notelocation = intent.getStringExtra("noteLocation");
notereminder = intent.getStringExtra("noteReminder");
Note receivednote = new Note(notetext, notecolor, notereminder, notelocation);
MyAdapter adapter = new MyAdapter(this, R.layout.list_item, notesArray);
notesArray.add(receivednote);
notesList.setAdapter(adapter);
//***************End Fetch data from intent***********//
}
}
我还附加了实现的自定义适配器。
公共类 MyAdapter 扩展 ArrayAdapter {
private Context mContext;
private int mResource;
private ArrayList<Note> mNotes = new ArrayList<>();
private String TAG = "Adapter Class";
public MyAdapter(@NonNull Context context, int resource, ArrayList<Note> objects) {
super(context, resource, objects);
mContext = context;
mResource = resource;
mNotes = objects;
}
@Override
public int getCount() {
return mNotes.size();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItem =convertView;
if(listItem==null){
listItem=LayoutInflater.from(mContext).inflate(mResource,parent,false);
Note currentNote = mNotes.get(position);
String text = mNotes.get(position).getText();
String color = mNotes.get(position).getColor();
String location = mNotes.get(position).getLocation();
String reminder = mNotes.get(position).getReminder();
TextView nttxt = listItem.findViewById(R.id.noteText);
TextView ntcolor = listItem.findViewById(R.id.textcolor);
TextView ntrem = listItem.findViewById(R.id.reminder);
TextView ntlocat = listItem.findViewById(R.id.location);
nttxt.setText(text);
ntcolor.setText(color);
ntrem.setText(reminder);
ntlocat.setText(location);
}
return listItem;
}
}
我记录了列表大小,它始终为 1。由于某种原因,它不会在 Activity#2 启动后保留当前元素。
任何建议将不胜感激。
【问题讨论】: