这是我第一次做一个Android应用程序,我在附注注释列表时遇到问题,当我尝试添加片段时会发生这种情况,这是连接MainActivity与片段的部分:protected void onCreate(Bundle savingInstanceState) { 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();
}
我需要解决注释列表不附注的问题,因为当我尝试在没有片段的情况下做到这一点时,一切都运行良好
正如我所见并假设您每次单击添加按钮时都会创建片段的新实例。相反,您应该声明一个全局变量并在添加按钮范围内使用它,以便避免不必要地创建片段的新实例。
例如。
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();
}
请告诉我这是否有帮助。