So, I have a TextView that generates a random number. I need that TextView to generate a random number every 472 ms, five times. So I tap the screen and a random number appears then 472 ms later another number appears, and this repeats until five random numbers have been displayed. I know I need to use a loop but what condition would I use to make sure that only five random numbers are generated?
Here's my XML:
<LinearLayout
android:id="@+id/linearLayout"
android:layout_width="0dp"
android:layout_height="0dp"
android:clickable="true"
android:onClick="perform_action"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_gravity="center_horizontal|center_vertical"
android:layout_marginBottom="75dp"
android:gravity="center"
android:textSize="400sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent" />
</RelativeLayout>
</LinearLayout>
</android.support.constraint.ConstraintLayout>
And my Java:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void perform_action(View view) {
Random r = new Random();
int minNumber = 1;
int maxNumber = 9;
int randomNumber = r.nextInt((maxNumber-minNumber)+1)+minNumber;
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(String.valueOf(randomNumber));
}
}
You should use rxjava
add these dependencies :
implementation 'io.reactivex.rxjava2:rxjava:2.2.2'
implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'
and then when you click your button :
final List< Integer > randomNumbers = new ArrayList<>( );
Observable.intervalRange( 0, 5, 0, 472, TimeUnit.MILLISECONDS )
.map( aLong -> {
int previous = randomNumbers.size( ) > 0 ? randomNumbers.get(
randomNumbers.size( ) - 1 ) : -1;
int randomNumber = generateRandomNumber();
while( randomNumber == previous ) generateRandomNumber();
randomNumbers.add( randomNumber );
return randomNumber;
} )
.observeOn( AndroidSchedulers.mainThread( ) )
.subscribe(integer -> {
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(String.valueOf(integer));
} );
private int generateRandomNumber( )
{
Random r = new Random( );
int minNumber = 1;
int maxNumber = 9;
return r.nextInt( ( maxNumber - minNumber ) + 1 ) + minNumber;
}
That's it!
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments