Android 小工具--随机数获取工具类

1.RandomDateUtil类代码


public class RandomDateUtil {
    
    
    public static int DATA(){
    
    //int
        int min=1;
        int max=100;
        Random random = new Random();
        return random.nextInt(max)%(max-min+1) + min;
    }
    public static String DATA2(){
    
    //String
        int min=1;
        int max=100;
        Random random = new Random();
        int num = random.nextInt(max)%(max-min+1) + min;
        return String.valueOf(num);
    }
}

2.布局文件

一个按钮,每次点击获取随机数

<?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">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:text="随机数获取"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

3.java代码


public class MainActivity extends AppCompatActivity {
    
    

    Button mButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mButton=findViewById(R.id.button);

        mButton.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View v) {
    
    
                mButton.setText(RandomDateUtil.DATA2());
            }
        });
    }
}

运行
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_46526828/article/details/108929321