Android’de, geliştiricilere anlamlı uygulamalar oluşturmaları için matematiksel ve mantıksal işlevler sağlayan birden çok kitaplık vardır.
Bu makalede, Android’de belirlenen bir aralıkta yani iki sayı arasında nasıl rastgele bir değer oluşturabileceğinizi göstereceğim.
Örneğimiz için tasarımımızı aşağıdaki gibi oluşturacağız. Butona basıldığında 50-100 arası rasgele bir sayı üreterek TextView’ de görüntülenmesini sağlayacağız.
activity_main.xml Kodları:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout 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" tools:context=".MainActivity"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="70dp" android:text="0" android:textSize="100sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/button" android:layout_width="151dp" android:layout_height="103dp" android:layout_marginTop="50dp" android:text="Rasgele Sayı Üret" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView" /> </androidx.constraintlayout.widget.ConstraintLayout> |
ActivityMain.java kodları:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | package com.example.randomsayi; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import java.util.concurrent.ThreadLocalRandom; public class MainActivity extends AppCompatActivity { Button btn; TextView txt; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn=(Button)findViewById(R.id.button); txt=(TextView)findViewById(R.id.textView); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int minimum = 50; int maksimum = 100; int rnd = ThreadLocalRandom.current().nextInt(minimum, maksimum); rnd = ThreadLocalRandom.current().nextInt(minimum, maksimum + 1); txt.setText(String.valueOf(rnd)); } }); } } |
Ekran Çıktısı: