Kotlin'de Aynı Aktivite İçinde Farklı Sınıfların Kullanımı
Aynı aktivite içinde farklı sınıfları kullanmak için genellikle aşağıdaki yöntemlerden biri tercih edilir:
View Binding ile Doğrudan Erişim
Fragment Kullanımı
Custom View'lar
Adapter Pattern
Bu örnekte, bir ana aktivite içinde iki farklı sınıfı (LoginManager ve ProfileManager) nasıl kullanabileceğimizi gösteren bir yapıyı XML layout'uyla birlikte paylaşacağım.
1. activity_main.xml (Ana Layout)
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp" tools:context=".MainActivity"> <!-- Durum göstergesi --> <TextView android:id="@+id/text_status" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Durum: Giriş yapılmadı" android:textSize="18sp" android:layout_marginBottom="16dp"/> <!-- Giriş bölümü --> <include android:id="@+id/login_section" layout="@layout/layout_login" android:layout_width="match_parent" android:layout_height="wrap_content"/> <!-- Profil bölümü (başlangıçta gizli) --> <include android:id="@+id/profile_section" layout="@layout/layout_profile" android:layout_width="match_parent" android:layout_height="wrap_content" android:visibility="gone"/> <Button android:id="@+id/btn_switch" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="16dp" android:text="Giriş Yap"/> </LinearLayout>
2. layout_login.xml (Giriş Bölümü)
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:background="#f0f0f0" android:padding="16dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Giriş Yap" android:textSize="20sp" android:textStyle="bold"/> <EditText android:id="@+id/edit_username" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp" android:hint="Kullanıcı Adı"/> <EditText android:id="@+id/edit_password" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp" android:hint="Şifre" android:inputType="textPassword"/> <Button android:id="@+id/btn_login" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:text="Giriş Yap"/> </LinearLayout>
3. layout_profile.xml (Profil Bölümü)
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:background="#f0f0f0" android:padding="16dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Profil Bilgileri" android:textSize="20sp" android:textStyle="bold"/> <TextView android:id="@+id/text_profile_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="8dp" android:text="İsim: " android:textSize="16sp"/> <TextView android:id="@+id/text_profile_email" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="8dp" android:text="Email: " android:textSize="16sp"/> <Button android:id="@+id/btn_logout" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:text="Çıkış Yap"/> </LinearLayout>
4. MainActivity.kt (Ana Aktivite)
import android.os.Bundle import android.view.View import android.widget.Button import android.widget.TextView import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { // UI Components private lateinit var textStatus: TextView private lateinit var btnSwitch: Button // Manager Classes private lateinit var loginManager: LoginManager private lateinit var profileManager: ProfileManager override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Initialize UI components textStatus = findViewById(R.id.text_status) btnSwitch = findViewById(R.id.btn_switch) // Initialize manager classes loginManager = LoginManager(this) profileManager = ProfileManager(this) // Set initial state updateUI(false) // Set button click listener btnSwitch.setOnClickListener { if (loginManager.isLoggedIn()) { loginManager.logout() updateUI(false) } else { if (loginManager.attemptLogin("user", "1234")) { profileManager.loadProfileData("user") updateUI(true) } else { textStatus.text = "Durum: Giriş başarısız" } } } } private fun updateUI(isLoggedIn: Boolean) { if (isLoggedIn) { textStatus.text = "Durum: Giriş yapıldı" btnSwitch.text = "Çıkış Yap" findViewById<View>(R.id.login_section).visibility = View.GONE findViewById<View>(R.id.profile_section).visibility = View.VISIBLE } else { textStatus.text = "Durum: Giriş yapılmadı" btnSwitch.text = "Giriş Yap" findViewById<View>(R.id.login_section).visibility = View.VISIBLE findViewById<View>(R.id.profile_section).visibility = View.GONE } } }
5. LoginManager.kt (Giriş İşlemleri Sınıfı)
import android.content.Context import android.widget.EditText class LoginManager(private val context: Context) { private var loggedIn = false fun isLoggedIn(): Boolean = loggedIn fun attemptLogin(username: String, password: String): Boolean { // Basit bir kontrol (gerçek uygulamada şifre hash'lenmelidir) val success = username == "user" && password == "1234" loggedIn = success return success } fun logout() { loggedIn = false } // View'lara erişim örneği fun getUsernameFromView(): String { val activity = context as MainActivity val editUsername = activity.findViewById<EditText>(R.id.edit_username) return editUsername.text.toString() } }
6. ProfileManager.kt (Profil İşlemleri Sınıfı)
import android.content.Context import android.widget.TextView class ProfileManager(private val context: Context) { fun loadProfileData(username: String) { // Gerçek uygulamada bu veriler bir API veya veritabanından alınır val profileData = when (username) { "user" -> Pair("Ahmet Yılmaz", "ahmet@example.com") else -> Pair("Bilinmeyen Kullanıcı", "email@example.com") } // View'ları güncelle val activity = context as MainActivity activity.findViewById<TextView>(R.id.text_profile_name).text = "İsim: ${profileData.first}" activity.findViewById<TextView>(R.id.text_profile_email).text = "Email: ${profileData.second}" } fun clearProfileData() { val activity = context as MainActivity activity.findViewById<TextView>(R.id.text_profile_name).text = "İsim: " activity.findViewById<TextView>(R.id.text_profile_email).text = "Email: " } }
Kullanım Senaryosu
Başlangıç Durumu: Uygulama açıldığında giriş ekranı görünür
Giriş Yapma: Kullanıcı adı "user" ve şifre "1234" girilip butona basıldığında:
LoginManager giriş işlemini kontrol eder
Başarılıysa ProfileManager profil verilerini yükler
UI güncellenir ve profil bölümü gösterilir
Çıkış Yapma: Çıkış butonuna basıldığında:
LoginManager çıkış işlemini yapar
UI tekrar giriş durumuna döner
Avantajlar
Kod Organizasyonu: Her sınıf kendi sorumluluğunu alır (Single Responsibility Principle)
Yeniden Kullanılabilirlik: Bu sınıflar başka aktivitelerde de kullanılabilir
Test Edilebilirlik: Her sınıf ayrı ayrı test edilebilir
Bakım Kolaylığı: Değişiklikler daha kontrollü yapılabilir
Dikkat Edilmesi Gerekenler
Context Kullanımı: Context'i dikkatli kullanın, memory leak'lere neden olabilir
UI Erişimi: Manager sınıflarının doğrudan UI elemanlarına erişmesi yerine, arayüzler kullanmak daha iyi bir yöntemdir
Yaşam Döngüsü: Manager sınıflarının aktivite yaşam döngüsüyle senkronize olması gerekebilir
Bu yapıyı daha da geliştirmek için Dependency Injection (örneğin Hilt) kullanabilir veya ViewModel'lar ile entegre edebilirsiniz.
0 Yorumlar