【问题标题】:Android: Why the listview.add function is always adding elements on position 1 in the listAndroid:为什么 listview.add 函数总是在列表中的位置 1 添加元素
【发布时间】: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 启动后保留当前元素。

任何建议将不胜感激。

【问题讨论】:

    标签: android android-listview


    【解决方案1】:

    问题在于,每次您在 Activity#2 中按下“保存”按钮时,您都会启动 Activity#1 的新实例,因此列表中只有一个注释。启动Activity2时需要使用startActivityForResult()方法,然后重写onActivityResult(),才能获取数据返回数据。 Activity#1 可能如下所示:

     public static final int NEW_NOTE_REQUEST = 23;
    @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);
                startActivityForResult(intentNoteEditor, NEW_NOTE_REQUEST);
                //Log.i("Lista",notesList.getCount()+"");
            }
        });
    
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // Check the returned result and parse the data
        if(resultCode == RESULT_OK && requestCode == NEW_NOTE_REQUEST){
            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);
    
        }
    }
    

    然后在 Activity#2 中:

    public void onSaveButtonClick(View view) {
        Intent intent = new Intent();
        // Add note data to intent
    
        // return the result to Activity#1
        setResult(RESULT_OK, intent);
        finish();
    }
    

    您还可以通过创建共享数据存储库来实现相同的功能,例如保存您的笔记列表的单例类,并且两个活动都将引用相同的笔记列表。

    【讨论】:

    • 我不知道 startActivityForResult。感谢您对此的帮助。非常感谢@wambada。
    猜你喜欢
    • 2020-11-09
    • 1970-01-01
    • 2019-03-12
    • 1970-01-01
    • 1970-01-01
    • 2020-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多