在Android中使用片段导致问题

xdyibdwo  于 4个月前  发布在  Android
关注(0)|答案(1)|浏览(96)

这是我第一次做一个android应用程序,我有问题的affiche笔记列表,当我试图添加片段时发生,这是连接主活动与片段的一部分:protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);

notesContainer = findViewById(R.id.notesContainer);
    noteList = new ArrayList<>();

    // Find the Button with ID myButton
    Button addButton = findViewById(R.id.myButton);
        // Set up a click listener for the "Add Note" button
        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Replace the current fragment with AddNoteFragment
                getSupportFragmentManager().beginTransaction()
                        .replace(R.id.fragmentContainer, new AddNoteFragment())
                        .addToBackStack(null) // Optional: Add transaction to back stack
                        .commit();
            }
        });
    LoadNotesFromPreferences();
    displayNote();
    }

字符串
我需要解决的问题,说明清单doent affiche,因为当我试图这样做,没有片段的每件事都工作得很好

zsbz8rwp

zsbz8rwp1#

正如我所看到的,假设你每次点击add按钮都在创建一个新的片段示例,你应该声明一个全局变量,并在add按钮作用域中使用它,这样就可以避免不必要的片段示例的创建。
比如说

noteList = new ArrayList<>();
    AddNoteFragment fragment = new AddNoteFragment();

    // Find the Button with ID myButton
    Button addButton = findViewById(R.id.myButton);
        // Set up a click listener for the "Add Note" button
        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Replace the current fragment with AddNoteFragment
                getSupportFragmentManager().beginTransaction()
                        .replace(R.id.fragmentContainer,fragment)// use variable so that it will use the same instance of fragment created above.
                        .addToBackStack(null) 
                        .commit();
            }
        });
    LoadNotesFromPreferences();
    displayNote();
    }

字符串
如果有用的话告诉我。

相关问题