I cant seem to find this answer anywhere. I've tried all the code i could find. I have an app that needs to make 2 random numbers, which the user will add together. Its a math practicing app.
Here is the xml code for the ui.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/num1"
android:layout_marginRight="50dp"
android:layout_marginEnd="50dp"
android:textSize="72sp"
android:layout_alignParentTop="true"
android:layout_toLeftOf="@+id/oper"
android:layout_toStartOf="@+id/oper" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/num2"
android:textSize="72sp"
android:layout_alignTop="@+id/oper"
android:layout_toRightOf="@+id/oper"
android:layout_toEndOf="@+id/oper"
android:layout_marginLeft="50dp"
android:layout_marginStart="50dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="+"
android:id="@+id/oper"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="72sp" />
The first textview and the third are random numbers to be generated by the app. The second textview is just an addition sign.
Here is my java code (keep in mind this is not a mainActivity)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_addition);
updateNums();
}
public void updateNums(){
final Random random = new Random();
final int randval = random.nextInt(10 - 1 + 1) + 1;
runOnUiThread(new Runnable() {
@Override
public void run() {
final TextView num1 = (TextView) findViewById(R.id.num1);
num1.setText(randval);
final TextView num2 = (TextView) findViewById(R.id.num2);
num2.setText(randval);
}});
}
You have to convert the random-value to a String - otherwise it is treated as a string-res
public void updateNums(){
final Random random = new Random();
final int randval = random.nextInt(10 - 1 + 1) + 1;
runOnUiThread(new Runnable() {
@Override
public void run() {
final TextView num1 = (TextView) findViewById(R.id.num1);
num1.setText(String.valueOf(randval));
final TextView num2 = (TextView) findViewById(R.id.num2);
num2.setText(String.valueOf(randval));
}});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.