Kotlin'de Aynı Aktivite İçinde Farklı Sınıfların Kullanımı

 

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:

  1. View Binding ile Doğrudan Erişim

  2. Fragment Kullanımı

  3. Custom View'lar

  4. 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
Copy
Download
Run
<?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
Copy
Download
Run
<?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
Copy
Download
Run
<?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)

kotlin
Copy
Download
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ı)

kotlin
Copy
Download
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ı)

kotlin
Copy
Download
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

  1. Başlangıç Durumu: Uygulama açıldığında giriş ekranı görünür

  2. 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

  3. Çıkış Yapma: Çıkış butonuna basıldığında:

    • LoginManager çıkış işlemini yapar

    • UI tekrar giriş durumuna döner

Avantajlar

  1. Kod Organizasyonu: Her sınıf kendi sorumluluğunu alır (Single Responsibility Principle)

  2. Yeniden Kullanılabilirlik: Bu sınıflar başka aktivitelerde de kullanılabilir

  3. Test Edilebilirlik: Her sınıf ayrı ayrı test edilebilir

  4. Bakım Kolaylığı: Değişiklikler daha kontrollü yapılabilir

Dikkat Edilmesi Gerekenler

  1. Context Kullanımı: Context'i dikkatli kullanın, memory leak'lere neden olabilir

  2. 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

  3. 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.

Yorum Gönder

0 Yorumlar