İşlem adımlarına göre personel yaş bilgisinin girildiği bir uygulama tasarlayalım. Personel sınıfının yaş özelliğini kapsülleyelim. Personel sınıfının yaş özelliğini 18’den küçük, 55’ten büyük girilmeyecek şekilde ayarlayalım.
Mobil uygulama geliştirme programında Empty Activity olacak şekilde bir proje oluşturunuz.
Uygulama ekranında bir EditText, bir Button ve bir TextView oluşturan şu kodu activity_main.xml içine yazınız.
<LinearLayout
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:orientation=”vertical”
app:layout_constraintBottom_toBottomOf=”parent”
app:layout_constraintEnd_toEndOf=”parent”
app:layout_constraintStart_toStartOf=”parent”
app:layout_constraintTop_toTopOf=”parent”>
<EditText
android:id=”@+id/editTextYas”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:minHeight=”48dp”
android:minWidth=”100dp”
android:hint=”Yaş” />
<Button
android:id=”@+id/buttonKaydet”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Kaydet”/>
<TextView
android:id=”@+id/textViewSonuc”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:text=”Sonuç”/>
</LinearLayout>
“Personel” adıyla yeni bir sınıf oluşturunuz.
Personel.java dosyasına şu kodu yazınız:
package com.example.kapsulleme;
public class Personel {
private int yas;
}
Alt+Ins tuşlarına basarak Generate penceresinden Getter and Setter komutunu çalıştırınız.
setYas metodunu şu kod ile değiştiriniz:
public void setYas(int yas) {
if(yas<18 || yas>55){
Log.e(“Kapsülleme”, “Hatalı yaş”);
yas = 18;
}
this.yas = yas;
}
MainActivity.java dosyasına şu kodu yazınız:
package com.example.kapsulleme;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText editTextYas = findViewById(R.id.editTextYas);
Button buttonKaydet = findViewById(R.id.buttonKaydet);
TextView textViewSonuc = findViewById(R.id.textViewSonuc);
buttonKaydet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int yas = Integer.parseInt(editTextYas.getText().toString());
Personel personel = new Personel();
personel.setYas(yas);
textViewSonuc.setText(Integer.toString(personel.getYas()));
}});
}
}
Run düğmesine tıklayarak uygulamayı çalıştırınız.
Değerleri girerek KAYDET düğmesine tıklayınız.
|