mardi 4 avril 2017

Generate a random number and results appear in TextView

Ill try and be specific as I can. This is my first post/question.

  1. No this is not for a school or work related project.
  2. I have researched and tried a number of things I saw with little results.

I am trying to create, on the Main activity, a button that generates a random number and sends the results to a Textview which is adjacent to the button on the same activity. The only thing I want to change is the contents of the TextView.

Here is my Java/Main Activity code:

package com.example.dannykennedyjr.diceroller;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;

import java.util.Random;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}
public void d4Results(View view) {
    TextView tv1 = (TextView) findViewById(R.id.d4TextView);
    final Random random = new Random();
    int d4Roll = random.nextInt(4)+1;
    tv1.setText(d4Roll);
}

}

This of course doesn't work, and anything I get to work opens up a new TextView and clears the current layout.

And my XML:

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="16dp"
    android:layout_marginStart="16dp"
    android:layout_marginTop="16dp"
    android:background="@android:color/black"
    android:onClick="d4Results"
    android:text="@string/roll_d4"
    android:textAlignment="center"
    android:textColor="@android:color/holo_red_dark"
    android:textSize="24sp"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/textView"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginEnd="16dp"
    android:layout_marginLeft="16dp"
    android:layout_marginRight="16dp"
    android:layout_marginStart="16dp"
    android:ems="10"
    android:hint="@string/roll_result"
    android:inputType="textPersonName"
    android:textAlignment="center"
    android:textSize="24sp"
    app:layout_constraintBaseline_toBaselineOf="@+id/button"
    app:layout_constraintHorizontal_bias="0.508"
    app:layout_constraintLeft_toRightOf="@+id/button"
    app:layout_constraintRight_toRightOf="parent" />

Any Help would be greatly appreciated. Thank You!




Aucun commentaire:

Enregistrer un commentaire