如何修复代码以防止其不响应我的点击/触摸,为什么有时只显示一个数字?

时间:2018-10-03 13:44:11

标签: android

我有一个项目,每472毫秒显示一次数字,五次。因此,您触摸屏幕并显示一个数字,然后在472毫秒后显示另一个数字,依此类推,直到显示五个数字。它在大多数情况下都有效,但有时它不响应我的单击/触摸,有时只显示一个数字。有关如何解决此问题的任何想法?

我的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>

还有我的Java:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public void perform_action(View view) {
    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;
    }
}

1 个答案:

答案 0 :(得分:0)

您应该更改此设置:

while (randomNumber == previous) generateRandomNumber();

对此:

while (randomNumber == previous) randomNumber = generateRandomNumber();

现在,一旦您进入while循环,它就会无限循环,因为条件始终是true