点击按钮生成一个1-100之间的随机数
activity_random_number.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayoutxmlns: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=".RandomNumber"><LinearLayoutandroid:orientation="vertical"android:layout_width="match_parent"android:layout_height="match_parent"android:gravity="center"><TextViewandroid:text="-"android:textSize="200sp"android:layout_width="wrap_content"android:layout_height="wrap_content" android:id="@+id/tv_random_number"tools:ignore="HardcodedText,MissingConstraints"/><Buttonandroid:text="随机数"android:layout_width="wrap_content"android:layout_height="wrap_content"android:id="@+id/btn_generate_random_number"tools:ignore="HardcodedText"/><TextViewandroid:text="点击按钮生成随机数"android:layout_width="wrap_content"android:layout_height="wrap_content" android:id="@+id/tv1"tools:ignore="HardcodedText"/></LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
RandomNumber.java
package com.weijun901.show;import android.view.View;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;public class RandomNumber extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_random_number);// 设置标题栏的文字getSupportActionBar().setTitle("随机数");TextView tvRandomNumber = findViewById(R.id.tv_random_number);View btnGenerateRandomNumber = findViewById(R.id.btn_generate_random_number);btnGenerateRandomNumber.setOnClickListener(view -> {int randomNumber = (int) (Math.random() * 100);tvRandomNumber.setText(String.valueOf(randomNumber));});}
}