我需要来自ActivityPlayers.java的arraylist(mNamelist),并在ActivityNewGame.java文件中使用该arraylist。另外,它应该同时更新。例如,在ActivityPlayers中,用户提供一个新名称或删除现有名称,它还应该将该名称插入或删除到ActivityNewGame中的相同列表中。

这是我的ActivityPlayers.java方法。当用户向mNamelist添加新名称时,将调用此方法。

private void addItem(int position) {
    /** Get user input (name) **/
    textAdd = findViewById(R.id.name_input);

    /** Add name to the list **/
    mNameList.add(position, new NameItem(textAdd.getText().toString().trim()));

    /** sort that list **/
    sortArrayList();

    /** save changes to shared preferences **/
    saveData();

    /** Show changed list to user **/
    mAdapter.notifyItemInserted(position);

    /** Clear the input field **/
    textAdd.getText().clear();

    /** Send namelist to ActivitynewGame **/
    Intent i = new Intent(ActivityPlayers.this, ActivityNewGame.class);
    i.putExtra("PlayerList", mNameList);
    startActivity(i);
}


这是我的ActivityNewGame:

    public class ActivityNewGame extends AppCompatActivity {
        private ArrayList<NewGamePlayerItem> mPlayerList;

        private RecyclerView mRecyclerView;
        private RecyclerView.Adapter mAdapter;
        private RecyclerView.LayoutManager mLayoutManager;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_new_game);

            mPlayerList = new ArrayList<>();
            Intent intent = getIntent();
            ArrayList<NameItem> mNameList = (ArrayList<NameItem>) intent.getSerializableExtra("PlayerList");

            /** Check if mNameList has any items in it. **/
            if (mNameList.size() != 0) {
            /** Loop through that arraylist and set its names into this Activity items. ("true" is for checkbox that this item has.) **/
                for (int i = 0; i < mNameList.size(); i++) {
                    mPlayerList.add(new NewGamePlayerItem(true, mNameList.get(i).getText1()));
                }
            }

            buildRecyclerView();
        }


这里的问题是我不想访问ActivityNewGame,我只想从ActivityPlayers传递该名称列表,并且当用户选择去制作一个新游戏(ActivityNewGame)时,该玩家列表就会在那里。那么我应该怎样做才能做到这一点呢?

最佳答案

您有几种选择:
将列表保存在Sqlite数据库中,并在活动中加载/重新加载。
在Intent对象中传递列表,请参见此question
在共享首选项中序列化

10-08 10:54