关于使用Android点击后产生随机数
案例如下:
package com.qiang.sifter;
import android.annotation.SuppressLint;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.qiang.But.MyUtils;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn =(Button)findViewById(R.id.btnse);
btn.setOnClickListener(this);
}
@SuppressLint("SetTextI18n")
@Override
public void onClick(View view) {
btn.setText(""+MyUtils.getRand(1,6));
}
}
在 btn.setText(MyUtils.getRand(1,6));出现问题的要进行类型转换
- 方法如下:TextView.setText("" + arg) btn.setText(""+MyUtils.getRand(1,6));
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:id="@+id/btnse"
android:layout_height="wrap_content"
android:text="掷色子"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
package com.qiang.But;
public class MyUtils {
public static int getRand(int a, int b) {
return (int) (Math.random() * (b - a + 1) + a);
}
}
欢迎大家交流沟通