Anladığım kadarıyla, mevcut FragmentEdit sınıfınızı düzenleyerek renk paletinden seçim yapıldığında notun arka plan rengini güncellemek istiyorsunuz. Bu, hem düzenleme modunda mevcut bir notun rengini güncellemenizi, hem de oluşturma modunda yeni bir not oluştururken arka plan rengini ayarlamanızı sağlayacak. Aşağıda, gerekli değişiklikleri içeren güncellenmiş FragmentEdit sınıfını bulabilirsiniz. Değişiklikleri açıklamalarla belirttim, böylece mevcut işlevselliği bozmadan ihtiyaçlarınıza uygun hale getirebilirsiniz.
Yapılacak Değişiklikler:
-
showColorPaletteDialog Metodunu Güncelleme:
- Renk seçildiğinde,
backgroundColor değişkenini güncelleyin.
- Düzenleme modunda iseniz, mevcut notun arka plan rengini güncellemek için
updateFlashcard metodunu çağırın.
- Oluşturma modunda iseniz, yeni not için
backgroundColor değerini ayarlayın.
- Seçilen rengi UI'ye yansıtın.
-
updateFlashcard Metodunu Genişletme:
backgroundColor değerini güncelleme haritasına ekleyin.
-
createFlashcard Metodunu Genişletme:
- Yeni oluşturulacak not için
backgroundColor değerini kullanın.
Aşağıda, bu değişiklikleri içeren güncellenmiş FragmentEdit sınıfını inceleyebilirsiniz:
package com.example.newflashcard;
import com.example.newflashcard.R.menu;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import com.google.android.material.appbar.MaterialToolbar;
import com.google.android.material.bottomappbar.BottomAppBar;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.text.SimpleDateFormat;
import java.util.Locale;
/**
* Flashcard düzenleme fragment'ı.
* Kullanıcıların flashcard bilgilerini güncelleyebileceği arayüzü yönetir.
*/
public class FragmentEdit extends Fragment {
private ScrollView scrollViewLayout;
private EditText editTextCategory, editTextTitle, editTextContent;
private MaterialToolbar fragmentToolbar;
private BottomAppBar fragmentBottomAppBar;
private TextView textViewTimestamp;
private TextView updateViewTimestamp;
private String flashcardId;
private String category, title, content;
private String backgroundColor; // Arka plan rengini tutar
private Long timeStamp, updatedAt;
private boolean isFavorite, isPinned;
// Verilerin değişip değişmediğini takip etmek için bayrak.
private boolean isDataChanged = false;
private List<String> hashtags;
private EditText hashtagsEditText;
/**
* Boş yapıcı metod.
*/
public FragmentEdit() {
// Gerekli boş yapıcı metod.
}
/**
* Yeni bir instance oluşturur.
*
* @param id Flashcard ID'si.
* @param category Kategori adı.
* @param title Başlık.
* @param content İçerik.
* @param favorite Favori durumu.
* @param pinned Sabit durumu.
* @param timestamp Oluşturulma zamanı.
* @param updatedAt Güncellenme zamanı.
* @param backgroundcolor Arka plan rengi.
* @param hashtags Hashtag listesi.
* @return Yeni FragmentEdit instance'ı.
*/
public static FragmentEdit newInstance(String id, String category, String title, String content, boolean favorite, boolean pinned, long timestamp, long updatedAt, String backgroundcolor, ArrayList<String> hashtags) {
FragmentEdit fragment = new FragmentEdit();
Bundle args = new Bundle();
args.putString("id", id);
args.putString("category", category);
args.putString("title", title);
args.putString("content", content);
args.putBoolean("favorite", favorite);
args.putBoolean("pinned", pinned);
args.putString("backgroundColor", backgroundcolor);
args.putLong("timestamp", timestamp);
args.putLong("updatedAt", updatedAt);
args.putStringArrayList("hashtags", hashtags);
fragment.setArguments(args);
return fragment;
}
/**
* Yeni bir instance oluşturur (yeni not).
*
* @return Yeni FragmentEdit instance'ı.
*/
public static FragmentEdit newInstance() {
FragmentEdit fragment = new FragmentEdit();
Bundle args = new Bundle();
// Yeni not için varsayılan değerler
args.putString("id", null);
args.putString("category", "");
args.putString("title", "");
args.putString("content", "");
args.putBoolean("favorite", false);
args.putBoolean("pinned", false);
args.putString("backgroundColor", ""); // Varsayılan arka plan rengi
args.putLong("timestamp", System.currentTimeMillis());
args.putLong("updatedAt", System.currentTimeMillis());
args.putStringArrayList("hashtags", new ArrayList<>());
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Eğer fragment içinde kendi menünüzü kullanıyorsanız setHasOptionsMenu'a gerek olmayabilir.
// setHasOptionsMenu(true); // Gerekirse aktif edin.
if (getArguments() != null) {
SharedPreferencesManager sharedPreferencesManager = new SharedPreferencesManager(getActivity());
boolean isNightModeEnabled = sharedPreferencesManager.isNightModeEnabled();
// Arka plan rengi - boş olup olmadığını kontrol edin
backgroundColor = getArguments().getString("backgroundColor", ""); // Varsayılan boş string
int color;
if (backgroundColor == null || backgroundColor.isEmpty()) {
// Eğer arka plan rengi boşsa varsayılan bir renk kullanın (örneğin beyaz)
color = ContextCompat.getColor(getActivity(), R.color.backgroundColor); // Buradaki R.color.default olsun tercih ettiğiniz varsayılan
} else {
// Arka plan rengi tanımlıysa, rengi çözümleyin
try {
color = Color.parseColor(backgroundColor);
} catch (IllegalArgumentException e) {
// Geçersiz renk koduysa varsayılan rengi kullan
color = ContextCompat.getColor(getActivity(), R.color.backgroundColor);
}
}
// Gece ve gündüz modu renk dönüşümünü uygulayın
if (isNightModeEnabled) {
color = MainActivity.reverseColorMap.getOrDefault(color, color);
} else {
color = MainActivity.colorMap.getOrDefault(color, color);
}
// Diğer değerleri al
flashcardId = getArguments().getString("id");
category = getArguments().getString("category");
title = getArguments().getString("title");
content = getArguments().getString("content");
isFavorite = getArguments().getBoolean("favorite");
isPinned = getArguments().getBoolean("pinned");
timeStamp = getArguments().getLong("timestamp");
updatedAt = getArguments().getLong("updatedAt");
hashtags = getArguments().getStringArrayList("hashtags");
}
else
{
// Yeni not modunda
category = "";
title = "";
content = "";
isFavorite = false;
isPinned = false;
timeStamp = System.currentTimeMillis();
updatedAt = System.currentTimeMillis();
hashtags = new ArrayList<>();
backgroundColor = ""; // Varsayılan arka plan rengi
}
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_edit, container, false);
// Görünümleri başlat.
editTextCategory = view.findViewById(R.id.editTextCategory);
editTextTitle = view.findViewById(R.id.editTextTitle);
editTextContent = view.findViewById(R.id.editTextContent);
fragmentToolbar = view.findViewById(R.id.fragmentToolbar);
fragmentBottomAppBar = view.findViewById(R.id.fragmentBottomAppBar);
textViewTimestamp = view.findViewById(R.id.textViewTimestamp);
updateViewTimestamp = view.findViewById(R.id.textViewUpdatedAt);
hashtagsEditText = view.findViewById(R.id.hashtagsEditTextView);
scrollViewLayout = view.findViewById(R.id.scrollViewContent);
// Menü'yü enflate et.
fragmentToolbar.inflateMenu(R.menu.fragment_options_menu);
// EditText ve diğer alanları doldur.
editTextCategory.setText(category);
editTextTitle.setText(title);
editTextContent.setText(content);
// Hashtag'ları virgülle ayrılmış şekilde EditText'e set et
if (hashtags != null && !hashtags.isEmpty()) {
String hashtagsString = TextUtils.join(", ", hashtags);
hashtagsEditText.setText(hashtagsString);
} else {
hashtagsEditText.setText("");
}
// Tarihleri formatla ve set et
Date date = new Date(timeStamp);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.getDefault());
textViewTimestamp.setText(sdf.format(date));
Date updatedDate = new Date(updatedAt);
SimpleDateFormat updatedSdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.getDefault());
updateViewTimestamp.setText(updatedSdf.format(updatedDate));
// Menü öğelerinin başlangıç durumunu ayarla.
initializeMenuItem(R.id.action_fav, isFavorite);
initializeMenuItem(R.id.action_pin, isPinned);
// Menü öğeleri için tıklama dinleyicisi ayarla.
fragmentToolbar.setOnMenuItemClickListener(this::handleMenuItemClick);
// Veri değişimini takip etmek için TextWatcher ekle.
SimpleTextWatcher simpleTextWatcher = new SimpleTextWatcher(() -> isDataChanged = true);
editTextCategory.addTextChangedListener(simpleTextWatcher);
editTextTitle.addTextChangedListener(simpleTextWatcher);
editTextContent.addTextChangedListener(simpleTextWatcher);
hashtagsEditText.addTextChangedListener(simpleTextWatcher); // Hashtag EditText için ekledik.
// Eğer Not Güncelleniyorsa gelen arkaplan rengine göre not ekranı, toolbar ve bottomappbar rengini ayarla.
if(getArguments() !=null){
setNoteScreenColors(backgroundColor,fragmentToolbar,fragmentBottomAppBar);
}
return view;
}
@Override
public void onResume() {
super.onResume();
// Ana aktivitenin toolbar ve FAB'ını gizle.
if (getActivity() instanceof MainActivity) {
((MainActivity) requireActivity()).hideToolbar();
((MainActivity) requireActivity()).hideFab();
}
}
@Override
public void onPause() {
super.onPause();
// Veri değişikliği varsa kaydet.
if (isDataChanged) {
saveChanges();
}
// Ana aktivitenin toolbar ve FAB'ını göster.
if (getActivity() instanceof MainActivity) {
//Not Düzenleme durumu ise
if(getArguments() !=null){
setNoteScreenColors("",fragmentToolbar,fragmentBottomAppBar);
resetDefaultScreenColors(fragmentToolbar,fragmentBottomAppBar);
}
((MainActivity) requireActivity()).showToolbar();
((MainActivity) requireActivity()).showFab();
}
}
/**
* Menü öğesini başlatır ve ikonunu günceller.
*
* @param menuItemId Menü öğesinin ID'si.
* @param isChecked Menü öğesinin başlangıçta seçili olup olmadığı.
*/
private void initializeMenuItem(int menuItemId, boolean isChecked) {
MenuItem menuItem = fragmentToolbar.getMenu().findItem(menuItemId);
if (menuItem != null) {
menuItem.setChecked(isChecked);
updateMenuIcon(menuItem, isChecked);
}
}
/**
* Menü öğesi tıklandığında işlemleri yönetir.
*
* @param item Tıklanan Menü öğesi.
* @return İşlemin başarılı olup olmadığı.
*/
private boolean handleMenuItemClick(MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.action_fav) { // Favori durumunu tersine çevir.
isFavorite = !isFavorite;
item.setChecked(isFavorite);
updateMenuIcon(item, isFavorite);
isDataChanged = true;
return true;
} else if (itemId == R.id.action_pin) { // Sabit durumu tersine çevir.
isPinned = !isPinned;
item.setChecked(isPinned);
updateMenuIcon(item, isPinned);
isDataChanged = true;
return true;
} else if (itemId == R.id.action_changecolor) { // Renk değiştirme işlemini burada gerçekleştirin.
showColorPaletteDialog();
// isDataChanged'ı burada ayarlamayın, çünkü renk seçimi sonrası kaydedilecek
return true;
} else if (itemId == R.id.action_delete) { // Flashcard'ı sil.
deleteFlashcard();
return true;
} else if (itemId == R.id.action_label) { // Etiket ekleme işlemini burada gerçekleştirin.
//Toast.makeText(getContext(), "Labels clicked", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
/**
* Menü öğesinin ikonunu günceller.
*
* @param item Güncellenecek Menü öğesi.
* @param isChecked Menü öğesinin seçili olup olmadığı.
*/
private void updateMenuIcon(MenuItem item, boolean isChecked) {
int itemId = item.getItemId();
if (itemId == R.id.action_fav) {
item.setIcon(isChecked ? R.drawable.ic_favorite_filled : R.drawable.ic_favorite_outlined);
} else if (itemId == R.id.action_pin) {
item.setIcon(isChecked ? R.drawable.ic_pin_filled : R.drawable.ic_pin_outlined);
}
// Diğer ikonlar için eklemeler yapabilirsiniz.
}
/**
* Flashcard üzerindeki değişiklikleri kaydeder.
*/
private void saveChanges() {
category = editTextCategory.getText().toString().trim();
title = editTextTitle.getText().toString().trim();
content = editTextContent.getText().toString().trim();
String hashtagsString = hashtagsEditText.getText().toString().trim();
List<String> hashtagsList;
if (!hashtagsString.isEmpty()) {
// Hashtag'ları parse et
hashtagsList = parseHashtags(hashtagsString);
} else {
// Hashtag metin kutusu boş ise boş liste ata
hashtagsList = new ArrayList<>();
// Boş string eklemek yerine boş liste bırakın
}
if (!category.isEmpty() && !title.isEmpty() && !content.isEmpty()) {
//Eğer Yeni Bir Not Oluşturuluyorsa
if (getArguments() == null || flashcardId == null) {
// Yeni flashcard oluştur
String id = FirebaseManager.getInstance().getUniqueKey(); // Benzersiz bir anahtar oluşturur
String bgColor = backgroundColor != null ? backgroundColor : ""; // Seçilen veya varsayılan arka plan rengi
long timestamp = System.currentTimeMillis(); // Şu anki zaman
createFlashcard(id, category, title, content, isFavorite, isPinned, bgColor, timestamp, timestamp, hashtagsList);
}
else
{
updateFlashcard(flashcardId, category, title, content, isFavorite, isPinned, backgroundColor, hashtagsList);
Toast.makeText(getActivity(), "Flashcard updated", Toast.LENGTH_SHORT).show();
isDataChanged = false;
}
} else {
Toast.makeText(getActivity(), "Please fill in all fields", Toast.LENGTH_SHORT).show();
}
}
/**
* Yeni bir Flashcard oluşturur
*
* @param id Flashcard ID'si.
* @param category Kategori adı.
* @param title Başlık.
* @param content İçerik.
* @param favorite Favori durumu.
* @param pinned Sabit durumu.
* @param hashtags Hashtag listesi.
*/
// Yeni bir flashcard oluşturma yöntemi
private void createFlashcard(String id, String category, String title, String content, boolean favorite, boolean pinned, String backgroundColor, long timestamp, long updatedAt, List<String> hashtags) {
Flashcard flashcard = new Flashcard(id, category, title, content, favorite, pinned, backgroundColor, timestamp, updatedAt, hashtags);
FirebaseManager.getInstance().addFlashcard(flashcard);
}
/**
* Flashcard verisini günceller.
*
* @param id Flashcard ID'si.
* @param category Kategori adı.
* @param title Başlık.
* @param content İçerik.
* @param favorite Favori durumu.
* @param pinned Sabit durumu.
* @param backgroundColor Arka plan rengi.
* @param hashtags Hashtag listesi.
*/
private void updateFlashcard(String id, String category, String title, String content, boolean favorite, boolean pinned, String backgroundColor, List<String> hashtags) {
Map<String, Object> updates = new HashMap<>();
updates.put("category", category);
updates.put("title", title);
updates.put("content", content);
updates.put("favorite", favorite);
updates.put("pinned", pinned);
updates.put("backgroundColor", backgroundColor); // Arka plan rengini ekle
updates.put("hashtags", hashtags); // Hashtag'ları ekliyoruz
long currentTimestamp = System.currentTimeMillis();
updates.put("updatedAt", currentTimestamp);
FirebaseManager.getInstance().updateFlashcard(id, updates);
}
/**
* Flashcard'ı siler.
*/
private void deleteFlashcard() {
FirebaseManager.getInstance().deleteFlashcard(flashcardId);
Toast.makeText(getActivity(), "Flashcard deleted", Toast.LENGTH_SHORT).show();
// Önceki fragment'a geri dön.
requireActivity().getSupportFragmentManager().popBackStack();
}
/**
* Kullanıcının girdiği hashtag stringini parse eder ve doğrular.
* Her hashtag'ın '#' ile başladığından emin olur.
*
* @param hashtagsString Kullanıcı tarafından girilen hashtag stringi.
* @return Doğru formatlanmış hashtag listesi.
*/
private List<String> parseHashtags(String hashtagsString) {
List<String> hashtagsList = new ArrayList<>();
if (!hashtagsString.isEmpty()) {
String[] splitHashtags = hashtagsString.split(",\\s*");
for (String tag : splitHashtags) {
if (!tag.startsWith("#")) {
tag = "#" + tag;
}
hashtagsList.add(tag);
}
}
return hashtagsList;
}
public void setNoteScreenColors(String backgroundColor, Toolbar toolbar, BottomAppBar bottomAppBar) {
// Night mode durumunu kontrol et
SharedPreferencesManager sharedPreferencesManager = new SharedPreferencesManager(getActivity());
boolean isNightModeEnabled = sharedPreferencesManager.isNightModeEnabled();
// Varsayılan renkleri tanımla
int defaultStatusBarColor = ContextCompat.getColor(getActivity(), R.color.navbar_color);
int defaultToolbarColor = ContextCompat.getColor(getActivity(), R.color.primaryColor);
int defaultBottomAppBarColor = ContextCompat.getColor(getActivity(), R.color.primaryColor);
int defaultScrollViewLayoutColor = ContextCompat.getColor(getActivity(), R.color.backgroundColor);
int defaultTextColor = ContextCompat.getColor(getActivity(), R.color.textColorPrimary);
// Arka plan rengi var mı kontrol et
int displayColor = defaultScrollViewLayoutColor;
if (backgroundColor != null && !backgroundColor.isEmpty()) {
try {
int parsedColor = Color.parseColor(backgroundColor);
if (isNightModeEnabled) {
// Gece modu için renk dönüştür
displayColor = MainActivity.reverseColorMap.getOrDefault(parsedColor, parsedColor);
} else {
// Gündüz modu için renk dönüştür
displayColor = MainActivity.colorMap.getOrDefault(parsedColor, parsedColor);
}
} catch (IllegalArgumentException e) {
// Geçersiz renk koduysa varsayılan rengi kullan
displayColor = defaultScrollViewLayoutColor;
}
}
// Arka plan rengiyle UI elementlerini güncelle
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getActivity().getWindow().setStatusBarColor(displayColor);
}
if (toolbar != null) {
toolbar.setBackgroundColor(displayColor);
}
if (scrollViewLayout != null) {
scrollViewLayout.setBackgroundColor(displayColor);
}
if (bottomAppBar != null) {
bottomAppBar.setBackgroundColor(displayColor);
}
// Eğer arka plan rengi beyaz ise ve gece modundaysak, özel renklendirme yap
if (isNightModeEnabled && (backgroundColor.equalsIgnoreCase("#FFFFFF") || backgroundColor.equalsIgnoreCase("#FFFFFFFF"))) {
int whiteTextColor = ContextCompat.getColor(getActivity(), R.color.textColorPrimaryForWhiteBackgroundIssue);
setContentTextColor(whiteTextColor);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getActivity().getWindow().setStatusBarColor(whiteTextColor);
}
if (toolbar != null) {
toolbar.setBackgroundColor(whiteTextColor);
}
if (bottomAppBar != null) {
bottomAppBar.setBackgroundColor(whiteTextColor);
}
} else {
// Varsayılan metin rengini ayarla
setContentTextColor(defaultTextColor);
}
}
// Fragment'tan çıkarken varsayılan renkleri geri yükleyin
public void resetDefaultScreenColors(Toolbar toolbar, BottomAppBar bottomAppBar) {
int defaultStatusBarColor = ContextCompat.getColor(getActivity(), R.color.navbar_color);
int defaultToolbarColor = ContextCompat.getColor(getActivity(), R.color.primaryColor);
int defaultBottomAppBarColor = ContextCompat.getColor(getActivity(), R.color.primaryColor);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getActivity().getWindow().setStatusBarColor(defaultStatusBarColor);
}
if (toolbar != null) {
toolbar.setBackgroundColor(defaultToolbarColor);
}
if (bottomAppBar != null) {
bottomAppBar.setBackgroundColor(defaultBottomAppBarColor);
}
}
private void setContentTextColor(int color) {
if (editTextContent != null) {
editTextCategory.setTextColor(color);
editTextTitle.setTextColor(color);
editTextContent.setTextColor(color);
hashtagsEditText.setTextColor(color);
}
}
/**
* Renk paleti dialogunu gösterir ve kullanıcı seçimini işler.
*/
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);
SharedPreferencesManager sharedPreferencesManager = new SharedPreferencesManager(getActivity());
boolean isNightMode = sharedPreferencesManager.isNightModeEnabled();
final int[] colors;
if (isNightMode) {
// GoogleKeep DarkTema Not Renkleri
colors = new int[]{
R.drawable.ic_clear_color, // Rengi temizleme ikonu
0xFF232531, // Koyu mavi
0xFF482E5B, // Koyu mor
0xFF264D3B, // Koyu yeşil
0xFF274255, // Orta mavi
0xFF256476, // Açık mavi
0xFF232530, // Koyu gri
0xFF692A18, // Koyu kahverengi
0xFF76172D, // Koyu kırmızı
0xFF232428, // Koyu siyah
0xFF4B443A // Orta kahverengi
};
} else {
// GoogleKeep DayTema Not Renkleri
colors = new int[]{
R.drawable.ic_clear_color, // Rengi temizleme ikonu
0xFFD3D6E3, // Açık mavi
0xFFE6D9ED, // Açık mor
0xFFD9E6DD, // Açık yeşil
0xFFD9E1E6, // Orta mavi
0xFFD9E6E9, // Açık mavi
0xFFD3D6E3, // Açık gri
0xFFE6D9D3, // Açık kahverengi
0xFFE6D3D9, // Açık kırmızı
0xFFD3D6E3, // Açık siyah
0xFFE6E3D9 // Orta kahverengi
};
}
AlertDialog dialog = builder.create();
// İlk renk öğesi (renk kaldırma)
View firstColorItem = LayoutInflater.from(getActivity()).inflate(R.layout.color_item, null);
ImageView firstColorIconImgView = firstColorItem.findViewById(R.id.colorIcon);
firstColorIconImgView.setImageResource(colors[0]);
firstColorItem.setOnClickListener(v -> {
// Renk temizleme işlemi (varsayılan rengi geri yükle)
backgroundColor = ""; // Varsayılan rengi temizle
setNoteScreenColors(backgroundColor, fragmentToolbar, fragmentBottomAppBar);
dialog.dismiss();
// Eğer düzenleme modundaysa backend'i güncelle
if (flashcardId != null) {
updateFlashcard(flashcardId, category, title, content, isFavorite, isPinned, backgroundColor, hashtags);
Toast.makeText(getActivity(), "Background color cleared", Toast.LENGTH_SHORT).show();
}
// Eğer oluşturma modundaysa, sadece UI'yi günceller ve kaydetme aşamasında kullanılacak
isDataChanged = true;
});
colorGrid.addView(firstColorItem, 0);
// Diğer renkler
for (int i = 1; i < colors.length; i++) {
final int color = colors[i];
View itemView = LayoutInflater.from(this).inflate(R.layout.color_item, null);
ImageView colorIcon = itemView.findViewById(R.id.colorIcon);
colorIcon.setBackgroundColor(color);
itemView.setOnClickListener(v -> {
String chosencolor = String.format("#%06X", (0xFFFFFF & color));
backgroundColor = chosencolor; // Seçilen rengi kaydet
// UI'yi güncelle
setNoteScreenColors(backgroundColor, fragmentToolbar, fragmentBottomAppBar);
dialog.dismiss();
// Eğer düzenleme modundaysa backend'i güncelle
if (flashcardId != null) {
updateFlashcard(flashcardId, category, title, content, isFavorite, isPinned, backgroundColor, hashtags);
Toast.makeText(getActivity(), "Background color updated", Toast.LENGTH_SHORT).show();
}
// Oluşturma modundaysa, sadece backgroundColor değişkeni güncellenir ve saveChanges() sırasında kullanılacak
isDataChanged = true;
});
colorGrid.addView(itemView);
}
dialog.show();
}
}
Açıklamalar ve Yapılan Değişiklikler:
-
backgroundColor Değişkeni:
- Sınıfın başında
backgroundColor adlı bir String değişkeni tanımlandı. Bu değişken, notun arka plan rengini tutmak için kullanılır.
-
onCreate Metodu:
backgroundColor değeri, fragment'a geçirilen argümanlardan alınıyor. Eğer bir renk atanmadıysa varsayılan olarak boş bırakılıyor.
- Renk kodunun geçerli olup olmadığını kontrol etmek için
try-catch bloğu eklendi. Geçersiz bir renk kodu girilmişse varsayılan renk kullanılacak.
-
saveChanges Metodu:
- Yeni bir not oluşturulurken
backgroundColor değeri createFlashcard metoduna aktarılıyor.
- Mevcut bir not güncellenirken
updateFlashcard metoduna backgroundColor parametresi ekleniyor.
-
createFlashcard Metodu:
- Yeni oluşturulan flashcard'a
backgroundColor parametresi ekleniyor.
-
updateFlashcard Metodu:
- Güncellenen flashcard'a
backgroundColor parametresi ekleniyor ve bu değer backend'e (Firebase) gönderiliyor.
-
showColorPaletteDialog Metodu:
- Kullanıcı bir renk seçtiğinde
backgroundColor değişkeni güncelleniyor.
- Seçilen renk, UI'ye yansıtılıyor (
setNoteScreenColors metodu ile).
- Eğer düzenleme modundaysa (
flashcardId != null), backend'deki mevcut notun arka plan rengi güncelleniyor.
- Oluşturma modundaysa,
backgroundColor değeri sadece değişken olarak güncelleniyor ve saveChanges metodunda kullanılacak.
-
Renk Temizleme (İlk Renk Öğesi):
- Renk temizleme ikonu seçildiğinde,
backgroundColor boşaltılıyor ve UI varsayılan renge dönüyor.
- Eğer düzenleme modundaysa, backend'deki notun arka plan rengi temizleniyor.
Ek Notlar:
- UI Güncellemeleri: Renk seçimi sonrası UI'nin hemen güncellenmesi için
setNoteScreenColors metodu çağrılıyor.
- Veri Değişikliği Takibi: Renk seçimi, veri değişikliği olduğu anlamına geldiği için
isDataChanged bayrağı true olarak ayarlanıyor. Bu sayede fragment durdurulurken değişiklikler otomatik olarak kaydediliyor.
- Geçersiz Renk Kodları: Kullanıcının geçersiz bir renk kodu girmesi durumunda uygulamanın çökmesini önlemek için
try-catch blokları eklendi.
Sonuç
Yukarıdaki değişikliklerle, FragmentEdit sınıfınız artık renk paletinden bir renk seçildiğinde, seçilen renge göre notun arka plan rengini güncelleyebilecek. Bu, hem mevcut notların düzenlenmesi sırasında renk güncellemelerini, hem de yeni not oluşturulurken arka plan renginin ayarlanmasını sağlayacaktır. Mevcut fonksiyonelliği koruyarak gerekli genişletmeleri yaptık, böylece diğer özellikler etkilenmemiş oldu.