// buttonAddFlashcard.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// String category = editTextCategory.getText().toString();
// String title = editTextTitle.getText().toString();
// String content = editTextContent.getText().toString();
//
// if (!category.isEmpty() && !title.isEmpty() && !content.isEmpty()) {
// String id = FirebaseManager.getInstance().getUniqueKey(); // Benzersiz bir anahtar oluşturur
// boolean favorite = false; // Varsayılan olarak false (isteğe bağlı)
// boolean pinned = false; // Varsayılan olarak false (isteğe bağlı)
// String backgroundColor = "#FFFFFF"; // Varsayılan renk (isteğe bağlı)
// long timestamp = System.currentTimeMillis(); // Şu anki zaman
//
// Flashcard flashcard = new Flashcard(id, category, title, content, favorite, pinned, backgroundColor, timestamp);
// FirebaseManager.getInstance().addFlashcard(flashcard);
//
// Toast.makeText(getActivity(), "Flashcard added", Toast.LENGTH_SHORT).show();
// getActivity().getSupportFragmentManager().popBackStack();
// } else {
// Toast.makeText(getActivity(), "Please fill in all fields", Toast.LENGTH_SHORT).show();
// }
// }
// });
code
<!-- Toolbar at the top -->
<com.google.android.material.appbar.MaterialToolbar
android:id="@+id/materialToolbarFrag"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="?attr/actionBarTheme"
app:navigationIcon="@drawable/ic_arrow_back" />
<!-- Content Area -->
<!-- Scroll içeriği için NestedScrollView -->
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<!-- İçerik alanı -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- Kategori, başlık ve içerik gibi öğeler -->
<EditText
android:id="@+id/editTextCategory"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Category"
android:singleLine="true" />
<EditText
android:id="@+id/editTextTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Title"
android:singleLine="true" />
<EditText
android:id="@+id/editTextContent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Content"
android:inputType="textMultiLine"
android:maxLines="10"
android:singleLine="false" />
<!-- Diğer içerikler buraya gelebilir -->
</LinearLayout>
</androidx.core.widget.NestedScrollView>
<!-- BottomAppBar kaydırıldığında gizlenecek -->
<com.google.android.material.bottomappbar.BottomAppBar
android:id="@+id/bottomAppBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="?attr/colorPrimary"
app:hideOnScroll="true"
tools:ignore="BottomAppBar">
<!-- CoordinatorLayout kullanarak ortadaki alanı dolduruyoruz -->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center">
<!-- Ortadaki TimeStamp TextView -->
<TextView
android:id="@+id/textViewTimestamp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="12:45 PM"
android:textColor="@android:color/white"
android:textSize="18sp" />
</RelativeLayout>
</com.google.android.material.bottomappbar.BottomAppBar>
Ana aktiviteden Note Ekleme fragmentini açtığımda iki toolbar aynı anda görüntüleniyor bu sorunuçöz -> package com.example.newflashcard;
Assistant
To resolve the issue of having two toolbars displayed simultaneously when you navigate to the "Note Ekleme" fragment, you can manage the visibility of the toolbars properly. Here are the steps to hide the activity's toolbar when navigating to the fragment and then show it again when navigating back:
Hide the Activity Toolbar in Fragment: When navigating to the fragment, hide the activity's toolbar. This is typically done in the fragment's onCreateView or onCreate method.
Show the Activity Toolbar on Fragment Exit: Once you exit the fragment (e.g., back press), show the activity's toolbar again.
Here's how you can modify your current code:
In the MainActivity:
Ensure that the toolbar in the MainActivity is properly initialized and managed. In the onCreate method, you should have:
In the fragment, you can manage the activity toolbar's visibility like this:
java
User
toolbar üzerindeki ikonlar ve optionsmenu ikonları karışmaya devam ediyor
Assistant
If the icons on the toolbar and options menu are getting mixed up or not displaying correctly, you may need to fine-tune the way you handle the setup and visibility of toolbars and menus between the activity and the fragment. Here are some suggestions to handle these issues:
Key Points to Manage Toolbars and Menus:
Unique IDs: Make sure both the activity and fragment toolbars have unique IDs. If both are called materialToolbar and are being set as the action bar, it can cause conflicts.
Lifecycle Correctness: Properly manage when you show and hide your activity's toolbar and fragment's toolbar using the fragment lifecycle methods. Ensure that toolbars are correctly shown or hidden based on the fragment visibility.
Menu Handling: In your fragment, carefully manage the menu items by using setHasOptionsMenu(true); and onCreateOptionsMenu to define what items should appear when the fragment is visible.
Here's how you can ensure proper setup and distinction:
MainActivity Code
Ensure that your MainActivity only sets its menu when onCreateOptionsMenu() is called for the activity's toolbar:
java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MaterialToolbar toolbar = findViewById(R.id.activityToolbar); // Ensure this ID is unique
setSupportActionBar(toolbar);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the activity's menu here
getMenuInflater().inflate(R.menu.activity_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle activity menu items here
int id = item.getItemId();
// Handle your action items here
return super.onOptionsItemSelected(item);
}
Fragment Code
Ensure that the fragment manages its own toolbar and menu independently:
Given the two menu XML files you've provided, it's important to ensure that the application's menus do not conflict when switching between the activity and the fragment. Here are a few steps to ensure a smooth transition and proper handling of options within your activity and fragment:
Separate Menu Handlers
Activity Menu:
The activity should only inflate its menu in onCreateOptionsMenu.
Manage the onOptionsItemSelected for activity-specific actions.
Fragment Menu:
The fragment should inflate its menu in onCreateOptionsMenu.
Handle its onOptionsItemSelected for fragment-specific actions.
Implementation Example
MainActivity.java
java
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.options_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_search:
// Handle search action
return true;
case R.id.action_change_recycleview_layout:
// Handle layout change
return true;
case R.id.action_night_mode:
// Handle night mode toggle
return true;
case R.id.action_settings:
// Handle settings action
return true;
case R.id.action_about:
// Handle about action
return true;
default:
return super.onOptionsItemSelected(item);
}
}
fragment_add_or_edit.java
java
User
Kodlarımı kontrol et ve hatayı bul, tek parça yaz -> package com.example.newflashcard;
public class MainActivity extends AppCompatActivity {
code
Assistant
Let's go through your implementation and resolve any issues related to the toolbar and menu management. The primary problem you've described is multiple toolbars being visible and menu items not being managed correctly when switching between the main activity and fragments. Here's a consolidated version of your code with explanations and corrections:
MainActivity.java
java
User
Cannot resolve symbol 'ActivityCompat'
Assistant
The issue with "Cannot resolve symbol 'ActivityCompat'" suggests that the ActivityCompat class from the AndroidX support library is not properly imported in your project. Here are a few steps to resolve this:
Step 1: Check Your Imports
Make sure that you have the correct import statement at the top of your Java file:
Instead of:
java
ActivityCompat activity = this;
You should use:
java
AppCompatActivity activity = this;
Ensure the following import exists, which allows you to use AppCompatActivity:
java
import androidx.appcompat.app.AppCompatActivity;
Step 2: Update your build.gradle (Module: app) File
Ensure that your build.gradle file includes the necessary dependencies for AndroidX. Check if it looks something like this:
gradle
dependencies {
// Other dependencies
// AppCompat for backwards compatibility
implementation 'androidx.appcompat:appcompat:1.6.1'
// Add other AndroidX dependencies as needed
}
Step 3: Sync Your Project
After ensuring your dependencies are correct, sync your project with Gradle files. Click "Sync Now" when prompted, or you can do it manually by going to File > Sync Project with Gradle Files.
Additional Considerations
Rebuild the Project: Sometimes, rebuilding the project can resolve such issues. To do this, go to Build > Rebuild Project.
Invalidate Caches and Restart: If none of the above steps work, try invalidating caches and restarting Android Studio (File > Invalidate Caches / Restart).
Replacing ActivityCompat with AppCompatActivity resolves the issue in this context since we are extending AppCompatActivity in MainActivity, and ActionMode should be started using AppCompatActivity. The proper use of AppCompatActivity ensures that UI elements and lifecycle methods are appropriately available. After making these changes, you should be able to resolve the "Cannot resolve symbol" error for ActivityCompat.
Your XML menu files look correctly structured for both the main activity and fragment. They define different menu items specific to their UI context. If you're experiencing issues with these menus not showing up or overlapping, make sure the implementation in your Java classes is correct. Below are key details to ensure each menu works appropriately in its context:
MainActivity Menu (activity_main.xml)
This is the menu for the MainActivity. It should be loaded and managed solely within the MainActivity:
java
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
adapter.filter(newText);
return true;
}
});
updateMenuIcon(menu); // If needed, update icons based on logic
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_search:
return true;
case R.id.action_change_recycleview_layout:
// Logic to change layout
return true;
case R.id.action_night_mode:
toggleNightMode();
return true;
// Add further cases for other menu items as required
default:
return super.onOptionsItemSelected(item);
}
}
Fragment Menu (fragment_add_or_edit.xml)
For the fragment, ensure that you correctly handle its menu and toolbar:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_add_or_edit, container, false);
MaterialToolbar toolbar = view.findViewById(R.id.materialToolbarFrag);
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
// Hide the activity toolbar
if (getActivity() != null) {
getActivity().findViewById(R.id.materialToolbar).setVisibility(View.GONE);
}
// Your existing code to handle fragment view initialization...
return view;
}
@Override
public void onDetach() {
super.onDetach();
// Show the activity toolbar again
if (getActivity() != null) {
getActivity().findViewById(R.id.materialToolbar).setVisibility(View.VISIBLE);
}
// Request activity to reset its menu and toolbar
invalidateOptionsMenu();
}
private void invalidateOptionsMenu() {
if (getActivity() != null) {
getActivity().invalidateOptionsMenu();
}
}
Explanation:
onCreateView: This method sets the custom toolbar for the fragment and hides the activity toolbar by finding it using getActivity().findViewById() and setting its visibility to GONE.
onDetach: This method is called when the fragment is detached from the activity, at which point you can restore the visibility of the activity's toolbar.
This solution ensures that the activity's toolbar is hidden when the fragment's toolbar is shown, and restored when you navigate back to the activity.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true); // Important to call this for fragment menu
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_add_or_edit, container, false);
MaterialToolbar toolbar = view.findViewById(R.id.fragmentToolbar);
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
// Hide the activity toolbar
if (getActivity() != null) {
getActivity().findViewById(R.id.activityToolbar).setVisibility(View.GONE);
}
return view;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the fragment's menu here
inflater.inflate(R.menu.fragment_menu, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle fragment menu items here
int id = item.getItemId();
// Handle your action items here
return super.onOptionsItemSelected(item);
}
@Override
public void onDetach() {
super.onDetach();
// Show the activity toolbar again when fragment is detached
if (getActivity() != null) {
getActivity().findViewById(R.id.activityToolbar).setVisibility(View.VISIBLE);
}
}
Steps to Avoid Icon Confusion:
Unique Toolbar Views: Ensure each toolbar has a unique identifier in XML (e.g., activityToolbar and fragmentToolbar).
Separate Menu XML Files: Use distinct XML files for menus for the activity and fragment (activity_menu.xml and fragment_menu.xml).
Clear Toolbar Menus: When switching between the activity and fragment, you can clear the toolbar's menu to ensure there's no residual menu items left:
java
@Override
public void onDetach() {
super.onDetach();
// Show the activity toolbar again when fragment is detached
if (getActivity() != null) {
Toolbar activityToolbar = getActivity().findViewById(R.id.activityToolbar);
activityToolbar.setVisibility(View.VISIBLE);
activityToolbar.getMenu().clear(); // Clear menu
}
}
By ensuring clear separation between activity and fragment settings and using unique IDs and XML resources, you should be able to resolve issues with mixed-up icons and correct menu display.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true); // This is critical for fragment-specific menus
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.fragment_menu, menu); // Inflate fragment menu
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_pin:
// Handle pin action
return true;
case R.id.action_changecolor:
// Handle color change
return true;
case R.id.action_fav:
// Handle favorite action
return true;
case R.id.action_delete:
// Handle delete action
return true;
case R.id.action_labels:
// Handle labels action
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onDetach() {
super.onDetach();
// Show the activity toolbar again when fragment is detached
if (getActivity() != null) {
getActivity().findViewById(R.id.activityToolbar).setVisibility(View.VISIBLE);
}
// Invalidate the options menu to refresh it, as needed
if (getActivity() != null) {
getActivity().invalidateOptionsMenu();
}
}
Managing Conflicts and Visibility
Hide/Restore Toolbar: Ensure that you correctly hide the activity toolbar (activityToolbar) when your fragment becomes active, and restore it when the fragment is not visible.
Check Fragment Lifecycle: Use fragment lifecycle methods to manage menu inflations. This ensures that each component handles its menus when active.
Toolbar IDs: Make sure toolbar IDs are unique in your layouts to avoid referencing the wrong toolbar.
By organizing the menus and actions as demonstrated, you ensure that only the relevant menu items are displayed and handled according to the current visible component (activity or fragment). This separation should help reduce conflicts and ensure that UI elements behave as expected.
private RecyclerView recyclerView;
private FlashcardAdapter adapter;
private ArrayList<Flashcard> flashcardList;
private SharedPreferencesManager sharedPreferencesManager;
private FloatingActionButton fab;
private Menu menu; // Add this line at the top of your MainActivity class
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferencesManager = new SharedPreferencesManager(this);
sharedPreferencesManager.applyNightMode();
recyclerView = findViewById(R.id.recyclerView);
fab = findViewById(R.id.fab);
flashcardList = new ArrayList<>();
adapter = new FlashcardAdapter(flashcardList);
recyclerView.setAdapter(adapter);
// Layout manager'ı ayarla
applyRecyclerViewLayout();
MaterialToolbar toolbar = findViewById(R.id.materialToolbar);
setSupportActionBar(toolbar);
// Flashcard'ları okuma örneği
FirebaseManager.getInstance().getFlashcards(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
flashcardList.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Flashcard flashcard = dataSnapshot.getValue(Flashcard.class);
flashcardList.add(flashcard);
}
adapter.filter(""); // Filtresiz listeleme
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Toast.makeText(MainActivity.this, "Failed to load data.", Toast.LENGTH_SHORT).show();
}
});
// FAB tıklama olayı
fab.setOnClickListener(view -> {
fragment_add_flashcard addFlashcardFragment = new fragment_add_flashcard();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, addFlashcardFragment);
transaction.addToBackStack(null);
transaction.commit();
fab.hide();
toolbar.setVisibility(View.GONE); // Hide the activity toolbar
});
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(this, recyclerView, new RecyclerTouchListener.ClickListener() {
@Override
public void onClick(View view, int position) {
//FirebaseManager.getInstance().deleteFlashcard(flashcardList.get(position).getId());
//Toast.makeText(MainActivity.this, "Flashcard Deleted.", Toast.LENGTH_SHORT).show();
fragment_add_or_edit addorEditNoteFragment = new fragment_add_or_edit();
Bundle bundle = new Bundle();
bundle.putString("category", flashcardList.get(position).getCategory());
bundle.putString("title", flashcardList.get(position).getTitle());
bundle.putString("content", flashcardList.get(position).getContent());
bundle.putString("timestamp", String.valueOf(flashcardList.get(position).getTimestamp()));
bundle.putBoolean("isPinned", flashcardList.get(position).isPinned());
bundle.putBoolean("isFavorite", flashcardList.get(position).isFavorite());
int color = ContextCompat.getColor(MainActivity.this, R.color.backgroundColor);
bundle.putInt("backgroundColor", flashcardList.get(position).getBackgroundColor().isEmpty() ? color : Color.parseColor(flashcardList.get(position).getBackgroundColor()));
addorEditNoteFragment.setArguments(bundle);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, addorEditNoteFragment);
transaction.addToBackStack(null);
transaction.commit();
toolbar.setVisibility(View.GONE); // Hide the activity toolbar
}
@Override
public void onLongClick(View view, int position) {
// Uzun tıklama işlemleri
}
}));
// Geri tuşu için callback
OnBackPressedCallback callback = new OnBackPressedCallback(true) {
@Override
public void handleOnBackPressed() {
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container);
if (fragment instanceof OnBackPressedListener) {
((OnBackPressedListener) fragment).onBackPressed();
} else {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
fab.show();
getSupportFragmentManager().popBackStack();
MaterialToolbar toolbar = findViewById(R.id.materialToolbar);
toolbar.setVisibility(View.VISIBLE); // Show again when returning
} else {
finish();
}
}
}
};
getOnBackPressedDispatcher().addCallback(this, callback);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.options_menu, menu);
this.menu = menu;
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
adapter.filter(newText);
return true;
}
});
// Menü öğesinin ikonunu başlangıç durumuna göre ayarla
updateMenuIcon(menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_search) {
return true;
}
if (id == R.id.action_night_mode) {
toggleNightMode();
return true;
}
if (id == R.id.action_change_recycleview_layout) {
// Mevcut görünüm türünü al
SharedPreferencesManager.ViewType currentViewType = sharedPreferencesManager.getRecyclerViewLayout();
// Yeni görünüm türünü belirle
SharedPreferencesManager.ViewType newViewType;
switch (currentViewType) {
case LIST:
newViewType = SharedPreferencesManager.ViewType.GRID;
break;
case GRID:
newViewType = SharedPreferencesManager.ViewType.STAGGERED_GRID;
break;
case STAGGERED_GRID:
default:
newViewType = SharedPreferencesManager.ViewType.LIST;
break;
}
// Yeni görünüm türünü ayarla
sharedPreferencesManager.setRecyclerViewLayout(newViewType);
// Menüdeki ikonları güncelle
updateMenuIcon(menu); // Değiştirilen ikonları güncelle
// RecyclerView layout'unu uygula
applyRecyclerViewLayout();
return true;
}
return super.onOptionsItemSelected(item);
}
public void startActionMode(final int position) {
AppCompatActivity activity = this;
activity.startActionMode(new ActionMode.Callback() {
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.getMenuInflater().inflate(R.menu.contextual_menu, menu);
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
int id = item.getItemId(); // Menü item kimliğini alın
if (id == R.id.action_delete) {
// Silme işlemi
flashcardList.remove(position);
adapter.notifyItemRemoved(position);
mode.finish();
return true;
} else if (id == R.id.action_edit) {
// Düzenleme işlemi
mode.finish();
return true;
} else {
return false;
}
}
@Override
public void onDestroyActionMode(ActionMode mode) {
// İşlem bittiğinde temizleme yapılabilir
}
});
}
private void toggleNightMode() {
sharedPreferencesManager.toggleNightMode();
recreate();
}
private void updateMenuIcon(Menu menu) {
// Menü öğesinin ikonunu görünüm türüne göre ayarla
SharedPreferencesManager.ViewType currentViewType = sharedPreferencesManager.getRecyclerViewLayout();
MenuItem item = menu.findItem(R.id.action_change_recycleview_layout);
switch (currentViewType) {
case LIST:
item.setIcon(R.drawable.ic_vertical_list_icon);
break;
case GRID:
item.setIcon(R.drawable.ic_gridview_icon);
break;
case STAGGERED_GRID:
item.setIcon(R.drawable.ic_staggeredgridview_icon); // Staggered grid için ikon ekle
break;
}
}
private void applyRecyclerViewLayout() {
SharedPreferencesManager.ViewType currentViewType = sharedPreferencesManager.getRecyclerViewLayout();
switch (currentViewType) {
case LIST:
recyclerView.setLayoutManager(new LinearLayoutManager(this));
break;
case GRID:
recyclerView.setLayoutManager(new GridLayoutManager(this, 2)); // 2 sütunlu grid
break;
case STAGGERED_GRID:
recyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)); // 2 sütunlu staggered grid
break;
}
adapter.notifyDataSetChanged(); // Notify the adapter of data changes
}
public interface OnBackPressedListener {
void onBackPressed();
}
// buttonAddFlashcard.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// String category = editTextCategory.getText().toString();
// String title = editTextTitle.getText().toString();
// String content = editTextContent.getText().toString();
//
// if (!category.isEmpty() && !title.isEmpty() && !content.isEmpty()) {
// String id = FirebaseManager.getInstance().getUniqueKey(); // Benzersiz bir anahtar oluşturur
// boolean favorite = false; // Varsayılan olarak false (isteğe bağlı)
// boolean pinned = false; // Varsayılan olarak false (isteğe bağlı)
// String backgroundColor = "#FFFFFF"; // Varsayılan renk (isteğe bağlı)
// long timestamp = System.currentTimeMillis(); // Şu anki zaman
//
// Flashcard flashcard = new Flashcard(id, category, title, content, favorite, pinned, backgroundColor, timestamp);
// FirebaseManager.getInstance().addFlashcard(flashcard);
//
// Toast.makeText(getActivity(), "Flashcard added", Toast.LENGTH_SHORT).show();
// getActivity().getSupportFragmentManager().popBackStack();
// } else {
// Toast.makeText(getActivity(), "Please fill in all fields", Toast.LENGTH_SHORT).show();
// }
// }
// });
package com.example.newflashcard;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import androidx.activity.OnBackPressedCallback;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import com.google.android.material.appbar.MaterialToolbar;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import androidx.appcompat.widget.SearchView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
// Instance variables
private RecyclerView recyclerView;
private FlashcardAdapter adapter;
private ArrayList<Flashcard> flashcardList;
private SharedPreferencesManager sharedPreferencesManager;
// FloatingActionButton to add new flashcard
private FloatingActionButton fab;
// Menu variable for later use in the class
private Menu menu;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Setting up shared preferences manager for night mode settings
sharedPreferencesManager = new SharedPreferencesManager(this);
sharedPreferencesManager.applyNightMode();
// Setting up RecyclerView and adapter
recyclerView = findViewById(R.id.recyclerView);
fab = findViewById(R.id.fab);
flashcardList = new ArrayList<>();
adapter = new FlashcardAdapter(flashcardList);
recyclerView.setAdapter(adapter);
// Apply default RecyclerView layout
applyRecyclerViewLayout();
// Setup and assign the toolbar
MaterialToolbar toolbar = findViewById(R.id.materialToolbar);
setSupportActionBar(toolbar);
// Firebase database listener for flashcards
FirebaseManager.getInstance().getFlashcards(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
flashcardList.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Flashcard flashcard = dataSnapshot.getValue(Flashcard.class);
flashcardList.add(flashcard);
}
adapter.filter(""); // Filter without any text to refresh display
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Toast.makeText(MainActivity.this, "Failed to load data.", Toast.LENGTH_SHORT).show();
}
});
// Handle floating action button to add a new flashcard
fab.setOnClickListener(view -> {
fragment_add_flashcard addFlashcardFragment = new fragment_add_flashcard();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, addFlashcardFragment);
transaction.addToBackStack(null);
transaction.commit();
fab.hide();
toolbar.setVisibility(View.GONE); // Hide the activity toolbar
});
// RecyclerTouchListener on RecyclerView items
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(this, recyclerView, new RecyclerTouchListener.ClickListener() {
@Override
public void onClick(View view, int position) {
fragment_add_or_edit addorEditNoteFragment = new fragment_add_or_edit();
Bundle bundle = new Bundle();
bundle.putString("category", flashcardList.get(position).getCategory());
bundle.putString("title", flashcardList.get(position).getTitle());
bundle.putString("content", flashcardList.get(position).getContent());
bundle.putString("timestamp", String.valueOf(flashcardList.get(position).getTimestamp()));
bundle.putBoolean("isPinned", flashcardList.get(position).isPinned());
bundle.putBoolean("isFavorite", flashcardList.get(position).isFavorite());
int color = ContextCompat.getColor(MainActivity.this, R.color.backgroundColor);
bundle.putInt("backgroundColor", flashcardList.get(position).getBackgroundColor().isEmpty()
? color : Color.parseColor(flashcardList.get(position).getBackgroundColor()));
addorEditNoteFragment.setArguments(bundle);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, addorEditNoteFragment);
transaction.addToBackStack(null);
transaction.commit();
toolbar.setVisibility(View.GONE); // Hide the activity toolbar
}
@Override
public void onLongClick(View view, int position) {
// Long click actions
startActionMode(position);
}
}));
// Handling Android back button to manage fragments and toolbar visibility
OnBackPressedCallback callback = new OnBackPressedCallback(true) {
@Override
public void handleOnBackPressed() {
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container);
if (fragment instanceof OnBackPressedListener) {
((OnBackPressedListener) fragment).onBackPressed();
} else {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStack();
toolbar.setVisibility(View.VISIBLE); // Show the toolbar again
fab.show();
} else {
finish();
}
}
}
};
getOnBackPressedDispatcher().addCallback(this, callback);
}
// Inflate activity options menu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.options_menu, menu);
this.menu = menu;
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
adapter.filter(newText);
return true;
}
});
// Adjust menu icons based on initial recycler view layout
updateMenuIcon(menu);
return true;
}
// Handle selection from activity menu
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_search) {
return true;
}
if (id == R.id.action_night_mode) {
toggleNightMode();
return true;
}
if (id == R.id.action_change_recycleview_layout) {
// Cycle through layout managers for RecyclerView
SharedPreferencesManager.ViewType currentViewType = sharedPreferencesManager.getRecyclerViewLayout();
SharedPreferencesManager.ViewType newViewType;
switch (currentViewType) {
case LIST:
newViewType = SharedPreferencesManager.ViewType.GRID;
break;
case GRID:
newViewType = SharedPreferencesManager.ViewType.STAGGERED_GRID;
break;
case STAGGERED_GRID:
default:
newViewType = SharedPreferencesManager.ViewType.LIST;
break;
}
sharedPreferencesManager.setRecyclerViewLayout(newViewType);
updateMenuIcon(menu); // Update icons based on new layout
applyRecyclerViewLayout(); // Apply new RecyclerView layout
return true;
}
return super.onOptionsItemSelected(item);
}
// Start action mode for editing or deleting a flashcard
public void startActionMode(final int position) {
ActivityCompat activity = this;
activity.startActionMode(new ActionMode.Callback() {
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.getMenuInflater().inflate(R.menu.contextual_menu, menu);
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_delete) {
flashcardList.remove(position);
adapter.notifyItemRemoved(position);
mode.finish();
return true;
} else if (id == R.id.action_edit) {
// Implement edit action if needed
mode.finish();
return true;
}
return false;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
// Cleanup if needed when action mode finishes
}
});
}
// Toggle night mode setting and recreate activity to apply changes
private void toggleNightMode() {
sharedPreferencesManager.toggleNightMode();
recreate();
}
// Update the icons in the menu based on current view type in RecyclerView
private void updateMenuIcon(Menu menu) {
SharedPreferencesManager.ViewType currentViewType = sharedPreferencesManager.getRecyclerViewLayout();
MenuItem item = menu.findItem(R.id.action_change_recycleview_layout);
switch (currentViewType) {
case LIST:
item.setIcon(R.drawable.ic_vertical_list_icon);
break;
case GRID:
item.setIcon(R.drawable.ic_gridview_icon);
break;
case STAGGERED_GRID:
item.setIcon(R.drawable.ic_staggeredgridview_icon);
break;
}
}
// Apply selected RecyclerView layout manager
private void applyRecyclerViewLayout() {
SharedPreferencesManager.ViewType currentViewType = sharedPreferencesManager.getRecyclerViewLayout();
switch (currentViewType) {
case LIST:
recyclerView.setLayoutManager(new LinearLayoutManager(this));
break;
case GRID:
recyclerView.setLayoutManager(new GridLayoutManager(this, 2)); // Grid with 2 columns
break;
case STAGGERED_GRID:
recyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
break;
}
adapter.notifyDataSetChanged();
}
// Interface for back pressed listener to handle custom fragment back actions
public interface OnBackPressedListener {
void onBackPressed();
}
}
fragment_add_or_edit.java
java
package com.example.newflashcard;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import com.google.android.material.appbar.MaterialToolbar;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class fragment_add_or_edit extends Fragment {
// UI components for adding or editing flashcards
private EditText editTextCategory;
private EditText editTextTitle;
private EditText editTextContent;
private TextView editTextTimeStamp;
// Various states and properties
private boolean isPinned;
private boolean isFavorite;
private int backgroundColor;
private boolean pinStateChanged = false;
private boolean favoriteStateChanged = false;
private boolean colorChanged = false;
private boolean noteDeleted = false;
// Original flashcard data
private String originalTitle;
private String originalCategory;
private String originalContent;
public fragment_add_or_edit() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true); // This makes the fragment menu appear
// Retrieve original flashcard data passed as arguments
if (getArguments() != null) {
originalCategory = getArguments().getString("category");
originalTitle = getArguments().getString("title");
originalContent = getArguments().getString("content");
isPinned = getArguments().getBoolean("isPinned");
isFavorite = getArguments().getBoolean("isFavorite");
backgroundColor = getArguments().getInt("backgroundColor");
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_add_or_edit, container, false);
// Set up the toolbar for this fragment
MaterialToolbar toolbar = view.findViewById(R.id.materialToolbarFragmentAddorEdit);
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
// Hide the activity's main toolbar
if (getActivity() != null) {
getActivity().findViewById(R.id.materialToolbar).setVisibility(View.GONE);
}
// Initialize UI elements
editTextCategory = view.findViewById(R.id.editTextCategory);
editTextTitle = view.findViewById(R.id.editTextTitle);
editTextContent = view.findViewById(R.id.editTextContent);
editTextTimeStamp = view.findViewById(R.id.textViewTimestamp);
if (getArguments() != null) {
editTextTitle.setText(originalTitle);
editTextCategory.setText(originalCategory);
editTextContent.setText(originalContent);
String timestamp = getArguments().getString("timestamp");
long timeInMillis = Long.parseLong(timestamp);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm", Locale.getDefault());
String formattedDate = sdf.format(new Date(timeInMillis));
editTextTimeStamp.setText(formattedDate);
view.setBackgroundColor(backgroundColor);
}
return view;
}
// Inflate fragment-specific menu
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.add_or_edit_fragment_options_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
MenuItem pinItem = menu.findItem(R.id.action_pin);
MenuItem favoriteItem = menu.findItem(R.id.action_fav);
pinItem.setIcon(isPinned ? R.drawable.ic_pin_filled : R.drawable.ic_pin_outlined);
favoriteItem.setIcon(isFavorite ? R.drawable.ic_favorite_filled : R.drawable.ic_favorite_outlined);
}
// Handle actions from the fragment menu
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_delete) {
noteDeleted = true;
if (getActivity() != null) {
getActivity().onBackPressed();
}
return true;
}
if (id == R.id.action_changecolor) {
showColorPaletteDialog();
return true;
}
if (id == R.id.action_pin) {
isPinned = !isPinned;
item.setIcon(isPinned ? R.drawable.ic_pin_filled : R.drawable.ic_pin_outlined);
pinStateChanged = true;
return true;
}
if (id == R.id.action_fav) {
isFavorite = !isFavorite;
item.setIcon(isFavorite ? R.drawable.ic_favorite_filled : R.drawable.ic_favorite_outlined);
favoriteStateChanged = true;
return true;
}
return super.onOptionsItemSelected(item);
}
// Show the color palette dialog for changing flashcard color
public void showColorPaletteDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
View dialogView = LayoutInflater.from(getActivity()).inflate(R.layout.color_picker_dialog, null);
builder.setView(dialogView);
GridLayout colorGrid = dialogView.findViewById(R.id.colorGrid);
final int[] colors = {
R.drawable.ic_clear_color,
0xFFB71C1C, 0xFF880E4F, 0xFF4A148C, 0xFF311B92, 0xFF1A237E,
0xFF0D47A1, 0xFF01579B, 0xFF006064, 0xFF004D40, 0xFF1B5E20,
0xFF33691E, 0xFF827717, 0xFFF57F17, 0xFFFF6F00, 0xFFE65100
};
AlertDialog dialog = builder.create();
// First color item for clearing color
View firstColorItem = LayoutInflater.from(getActivity()).inflate(R.layout.color_item, null);
ImageView firstColorIcon = firstColorItem.findViewById(R.id.colorIcon);
firstColorIcon.setImageResource(colors[0]);
firstColorItem.setOnClickListener(v -> {
updateFlashcardColor(0, false);
dialog.dismiss();
});
colorGrid.addView(firstColorItem, 0);
// Add other colors to the dialog
for (int i = 1; i < colors.length; i++) {
final int color = colors[i];
View itemView = LayoutInflater.from(getActivity()).inflate(R.layout.color_item, null);
ImageView colorIcon = itemView.findViewById(R.id.colorIcon);
colorIcon.setBackgroundColor(color);
itemView.setOnClickListener(v -> {
updateFlashcardColor(color, true);
dialog.dismiss();
});
colorGrid.addView(itemView);
}
dialog.show();
}
// Update flashcard with selected color
private void updateFlashcardColor(int color, boolean hasColor) {
String hexColor = "";
int themecolor = 0;
if (hasColor) {
hexColor = String.format("#%06X", (0xFFFFFF & color));
getView().setBackgroundColor(Color.parseColor(hexColor));
} else {
hexColor = "";
themecolor = AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES
? ContextCompat.getColor(requireContext(), R.color.backgroundColor)
: ContextCompat.getColor(requireContext(), R.color.backgroundColor);
getView().setBackgroundColor(themecolor);
}
backgroundColor = hasColor ? color : themecolor;
colorChanged = true;
}
// Handle fragment detachment to restore activity UI elements
@Override
public void onDetach() {
super.onDetach();
if (getActivity() != null) {
getActivity().findViewById(R.id.materialToolbar).setVisibility(View.VISIBLE);
}
// Invalidate the options menu to refresh when this fragment is detached
invalidateOptionsMenu();
}
private void invalidateOptionsMenu() {
if (getActivity() != null) {
getActivity().invalidateOptionsMenu();
}
}
}
Key Points to Consider:
Unique Toolbar IDs: Ensure each toolbar has a unique ID in its corresponding layout (activity and fragment) to avoid ambiguity.
Menu Management: Make sure to invoke setHasOptionsMenu(true) in the fragment, which allows the fragment to have its own menu. Also, manage the options menu separately in each component.
Visibility Control: Properly handle visibility of the toolbars when switching from activity to fragment and back using methods like setVisibility().
Back Navigation: Manage navigation using the OnBackPressedCallback, making sure to show relevant UI components when going back.
Fragment Transactions: Ensure that your fragment transactions are managed precisely with addToBackStack() for better back navigation handling.
With the above code organization and tips, your application should handle transitions smoothly between the activity and fragments, with each having the appropriate menu and toolbar visible at any time.
java
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true); // Important for fragment-specific menu
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_add_or_edit, container, false);
// Set up your custom toolbar for the fragment
MaterialToolbar toolbar = view.findViewById(R.id.materialToolbarFragmentAddorEdit);
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
// Hide the activity's main toolbar
if (getActivity() != null) {
getActivity().findViewById(R.id.materialToolbar).setVisibility(View.GONE);
}
return view;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.fragment_add_or_edit, menu);
MenuItem pinItem = menu.findItem(R.id.action_pin);
MenuItem favoriteItem = menu.findItem(R.id.action_fav);
// Initialize pin and favorite icons based on their states
pinItem.setIcon(isPinned ? R.drawable.ic_pin_filled : R.drawable.ic_pin_outlined);
favoriteItem.setIcon(isFavorite ? R.drawable.ic_favorite_filled : R.drawable.ic_favorite_outlined);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_pin:
isPinned = !isPinned;
item.setIcon(isPinned ? R.drawable.ic_pin_filled : R.drawable.ic_pin_outlined);
return true;
case R.id.action_changecolor:
showColorPaletteDialog();
return true;
case R.id.action_fav:
isFavorite = !isFavorite;
item.setIcon(isFavorite ? R.drawable.ic_favorite_filled : R.drawable.ic_favorite_outlined);
return true;
case R.id.action_delete:
// Handle delete action
return true;
// Add further cases for other menu items as required
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onDetach() {
super.onDetach();
if (getActivity() != null) {
// Show the activity toolbar again
getActivity().findViewById(R.id.materialToolbar).setVisibility(View.VISIBLE);
}
}
Key Points to Ensure Proper Functionality:
Separate Actions: Each menu file should only be accessed and managed within its corresponding activity or fragment.
Unique File Names: Ensure your menu XML files are correctly linked and unique to avoid accidental overlap.
Lifecycle Management: Make sure to handle the activity or fragment lifecycle correctly. Ensure that the appropriate toolbar visibility toggling is done during transitions.
Inflated Once: Avoid re-inflating or manipulating the same menu object from multiple components unless intended for central management.
UI Consistency: Verify that UI components such as toolbars have unique IDs where needed and are not reused unless the setup is intended for shared components.
These approaches manage the menu interactions in each UI context effectively, reducing unexpected behavior between the activity and fragment views.