Ill try and be specific as I can. This is my first post/question.
- No this is not for a school or work related project.
- 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.exampal.appname;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Random;
public class MainActivity2 extends AppCompatActivity {
Button generate;
TextView rendom_text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
rendom_text = findViewById(R.id.rendom_text);
generate = findViewById(R.id.generate);
generate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
rendom_text.setText(generat(10));
}
});
}
private String generat(int lenth) {
char[] chars = "ABCDEFGHIJKALMNOPQRSTUVWXYZ1234567890".toCharArray();
StringBuilder stringBuilder = new StringBuilder();
Random random = new Random();
for (int j = 0; j < lenth; j++) {
char c = chars[random.nextInt(chars.length)];
stringBuilder.append(c);
}
return stringBuilder.toString();
}
}
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:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/background"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity2">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="@+id/rendom_text"
android:layout_width="80pt"
android:layout_height="50dp"
android:layout_marginTop="10dp"
android:background="@drawable/main_background"
android:textColor="#fff" />
<Button
android:id="@+id/generate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50pt"
android:background="@drawable/main_background"
android:gravity="center"
android:text="generate" />
</LinearLayout>
</ScrollView>
</LinearLayout>
Comments
Post a Comment