I'm attempting to work on a simple first Android app, and while eventually it will be a shake-to-activate app, right now it still works with the click of a button because I need to be able to test it on the emulator I have.
The end goal for the app is to, when the device is shaken, choose one random number out of three (each corresponds to a Character from a show) and read that number to fade in an image of that character. Directly after, it fades in a random quote from an array of quotes from that specific character.
Currently, I'd gotten the app working to the point where, when I clicked the button, the app chose a character, and a quote from the array for that character, and was able to fade the quote in. In trying to implement the image fading in, I've done something that makes the app crash when I try to run it.
I'm sure it'll be some stupid mistake, but it would be fantastic if it could be found.
The project has four class files: MainActivity.java, DoctorWho.java, Nine.java, Ten.java, and Eleven.java. Nine, Ten, and Eleven are all nearly identical, just using different quotes.
In trying to add the image fade-in, I added it to DoctorWho.java, here:
public class DoctorWho {
private Nine mNine = new Nine();
private Ten mTen = new Ten();
private Eleven mEleven = new Eleven();
private ImageView mImageView1;
private ImageView mImageView2;
private ImageView mImageView3;
int randomNumber = 0;
public String getDoctorQuote() {
String quote = "";
// Choose a Random number out of three values
Random randomGenerator = new Random();
int randomNumber = randomGenerator.nextInt(3);
// Use that value to choose which of the Doctors to get a quote from
if (randomNumber == 0) {
// Quote from Nine
quote = mNine.getQuote();
}
else if (randomNumber == 1) {
// Quote from Ten
quote = mTen.getQuote();
}
else if (randomNumber == 2) {
// Quote from Eleven
quote = mEleven.getQuote();
}
else {
quote = "Error";
}
return quote;
}
public void animateDoctor() {
if (randomNumber == 0) {
animateNinthDoctor();
}
else if (randomNumber == 1) {
animateTenthDoctor();
}
else if (randomNumber == 2) {
animateEleventhDoctor();
}
}
private void animateNinthDoctor() {
AlphaAnimation fadeInAnimation = new AlphaAnimation(0, 1);
fadeInAnimation.setDuration(1500);
fadeInAnimation.setFillAfter(true);
mImageView1.setAnimation(fadeInAnimation);
}
private void animateTenthDoctor() {
AlphaAnimation fadeInAnimation = new AlphaAnimation(0, 1);
fadeInAnimation.setDuration(1500);
fadeInAnimation.setFillAfter(true);
mImageView2.setAnimation(fadeInAnimation);
}
private void animateEleventhDoctor() {
AlphaAnimation fadeInAnimation = new AlphaAnimation(0, 1);
fadeInAnimation.setDuration(1500);
fadeInAnimation.setFillAfter(true);
mImageView3.setAnimation(fadeInAnimation);
}
In my MainActivity.java file, I try to run the animation on-click here:
#Override
public void onClick(View arg0) {
String quote = mDoctorWho.getDoctorQuote();
mDoctorWho.animateDoctor();
// mQuoteLabel is the TextView where the quotes are displayed
mQuoteLabel.setText(quote);
animateQuoteIn();
}
The app still starts up fine, and no errors are shown before I run it on the emulator. When I click on the button that should run this sequence, the app crashes. There are no errors shown in the console, and I wasn't able to find a specific line in the LogCat view - I may be looking in the wrong place though. Let me know if updating the post with more code would be helpful in finding what is causing the crash.
Try changing you DoctorWho class as following:
Also have you initialized mImageView1,mImageView2,mImageView3 inside DoctorWho class???
public class DoctorWho {
private Nine mNine = new Nine();
private Ten mTen = new Ten();
private Eleven mEleven = new Eleven();
private ImageView mImageView1;
private ImageView mImageView2;
private ImageView mImageView3;
int randomNumber = 0;
public String getDoctorQuote() {
String quote = "";
// Choose a Random number out of three values
Random randomGenerator = new Random();
randomNumber = randomGenerator.nextInt(3);//<--- don't create new randonNumber
// Use that value to choose which of the Doctors to get a quote from
if (randomNumber == 0) {
// Quote from Nine
quote = mNine.getQuote();
}
else if (randomNumber == 1) {
// Quote from Ten
quote = mTen.getQuote();
}
else if (randomNumber == 2) {
// Quote from Eleven
quote = mEleven.getQuote();
}
else {
quote = "Error";
}
return quote;
}
public void animateDoctor() {
ImageView imageView=null;
if (randomNumber == 0) {
imageView=mImageView1;
}
else if (randomNumber == 1) {
imageView=mImageView2;
}
else if (randomNumber == 2) {
imageView=mImageView3;
}
AlphaAnimation fadeInAnimation = new AlphaAnimation(0, 1);
fadeInAnimation.setDuration(1500);
fadeInAnimation.setFillAfter(true);
imageView.setAnimation(fadeInAnimation);
}
}
Related
So as the title says im struggling to add a value to an integer and then pass it to another class that uses it, then this class will pass it to the next and then that one will pass it over to the main class. Its an integer that changes the stat template of the enemies in my small game im writing.
I have tried to make constructors in two of my classes as I thought that was the problem, Ive tried to see if they work by passing some messages in them.
The problem seems to be that when I save something in the "private int l" It dosnt actually change the value of that int and I cant figure out why that is.
Here is my code, its probably not very pretty so if you have any suggestions to structure changes that I might wanna do please feel free too let me know!
Thanks in advance!
import java.util.Scanner;
public class Stor {
public static void main(String[] args) {
Scanner user_Input = new Scanner(System.in);
Menu user = new Menu();
EnemyValue monster = new EnemyValue();
user.namn();
user.AnvNamn = user_Input.next();
user.introMeny();
user.difficulty();
System.out.println(“Your enemy has " + monster.HP + " HP and " +
monster.DMG + " Damage" );
user_Input.close();
}
}
class Menu {
Scanner user_Input = new Scanner(System.in);
String AnvNamn;
String difficultySvar;
String nivåSvar;
int svar;
private int i; /
private int l;
public int getL() {
return l;
}
boolean difficultyLoop = true;
boolean felLoop = true;
void introMeny() {
System.out.println(“Welcome " + AnvNamn + "!");
}
void namn() {
System.out.print(“Pick a name: “);
}
void difficulty() {
do {
System.out.println("\nWhat level do you want ?\n1 = Easy.\n2 =
Medium.\n3 = Hard.”);
svar = user_Input.nextInt();
if (svar == 1) {
System.out.println(“Your not very brave are you ? Are you sure
this is how you wanna play ?”);
difficultySvar = user_Input.next();
if (difficultySvar.equalsIgnoreCase(“Yes”)) {
difficultyLoop = false;
l = 1;
} // If ja 1
else if (difficultySvar.equalsIgnoreCase(“Nej”)) {
System.out.println(“Ahh good! I figuerd you would change
your mind.”);
}
else
System.out.println(“I don’t understand….”);
} // if 1
else if (svar == 2) {
System.out.println(“Not to hard or to easy, a good choice! But
maybe you want to go for something harder ? Or maybe easier ?");
difficultySvar = user_Input.next();
if (difficultySvar.equalsIgnoreCase(“Yes”)) {
difficultyLoop = false;
l = 2;
} // if ja 2
else if (difficultySvar.equalsIgnoreCase(“No”)) {
System.out.println(“I sure hope you don’t pick the easy
way…..”);
}
else
System.out.println("I don’t understand….");
} // Else if 2
else if (svar == 3) {
System.out.println(“Damn! We have a big player here! Are you
sure you can handle this ?");
difficultySvar = user_Input.next();
if (difficultySvar.equalsIgnoreCase(“Yes”)) {
difficultyLoop = false;
l = 3;
} // If ja 3
else if (difficultySvar.equalsIgnoreCase(“No”)) {
System.out.println(“Wuss.”);
}
else
System.out.println(“I don’t understand….”);
} // Else if 3
else {
if (i == 0) {
System.out.println(“Ha you thought you could fool the system?!
The system fools you!”);
System.out.println(“Nah but seriously, you can only choose
between 1-3…..“);
i++;
} // if i 0
else if (i == 1) {
System.out.println(“Alright I get that its hard but
COMEON!”);
i++;
} // if i 1
else if (i == 2) {
System.out.println(“OKEY YOU GET ONE LAST CHANCE!!”);
i++;
} // if i 2
else if (i == 3) {
System.out.println(“Alright thats it…. GET OUT!”);
System.exit(0);
} // if i 3
} // Else
} // do while loop
while(difficultyLoop == true);
} //Difficulty metod.
} // Menu class.
class Nivå {
//Menu level = new Menu();
//int levelChoice = level.getL();
int levelChoice;
private int enemyLife;
public int getenemyLife() {
return enemyLife;
}
private int enemyDMG;
public int getenemyDMG() {
return enemyDMG;
}
Nivå(){
Menu level = new Menu();
levelChoice = level.getL();
System.out.println("testNivå");
}
void fiendeLiv() {
if (levelChoice == 1)
enemyLife = 100;
else if (levelChoice == 2)
enemyLife = 150;
else if (levelChoice == 3)
enemyLife = 200;
} // fiendeliv method
void fiendeDMG() {
if (levelChoice == 1)
enemyDMG = 5;
else if (levelChoice == 2)
enemyDMG = 10;
else if (levelChoice == 3)
enemyDMG = 15;
} // fiendeDMG method
} // Nivå class
class EnemyValue {
public int HP;
public int DMG;
int maxLife;
int maxDMG;
EnemyValue(){
Nivå stats = new Nivå();
maxLife = stats.getenemyLife();
maxDMG = stats.getenemyDMG();
System.out.println("TestEnemyValue");
}
void rank1() {
HP = maxLife;
DMG = maxDMG;
} // rank1 easy method
} // EnemyValue class
You say that when you save something in l (poor choice of a variable name, by the way) it does not save the value. How do you know that? Where in the code do you check whether the value is saved?
In the constructor for class Nivå you create a new Menu and then call getL() on that menu before you have ever set the value of that variable.
Everything runs at the start of your public static void main(String[] args) method, and nothing will run if its instructions are not in there. For example, you are not actually creating any Niva objects in the main method, so the Niva constructor is never called. That is one issue. The other is your constructors are creating new instances of objects and then getting their values; this gives you empty values from a brand new object:
Nivå(){
Menu level = new Menu(); // Don't do this. This is an empty menu
levelChoice = level.getL(); // Getting the blank L value from the empty menu
System.out.println("testNivå");
}
Instead, you need to define constructors with parameters to pass the values into the class like this:
Nivå(int level){ // add an int parameter
levelChoice = level; // Direct assignment
fiendeDMG(); // Call this in the constructor to set up your last value
System.out.println("testNivå");
}
Then, when you call the constructor (which you must if you want it to exist), include the parameter. Inside the Stor class:
public static void main(String[] args) {
Scanner user_Input = new Scanner(System.in);
Menu user = new Menu();
user.namn();
user.AnvNamn = user_Input.next();
user.introMeny();
user.difficulty(); // Run this before creating the other classes; you need the l value
Nivå niva = new Nivå(user.getL()); // Creates new Niva while also assigning l to the levelChoice and then getting DMG
EnemyValue monster = new EnemyValue(/*add some parameters for life and dmg*/);
}
There is still more that needs to be done, like modifying the constructor of the EnemyLevel. Just remember that methods are never called unless they connect to something running from main and use parameters in functions and constructors to pass on data to other objects. Hope this helps.
I'm trying to build a calculator that subtracts one textview from another. One of the textview has a constant value 5. The other textview gets its value after a user presses buttons from 0 to 9. There's also a button for a decimal sign (dot). So, for example, if I press buttons 4, 5, ., 6 and 7, the textview will show 45.67 and a third textview will present the answer (40.67).
This example works fine. But my problem is that I want to limit the number of integers (numbers before the dot) to three. Although I can do this by simply adding setMaximumIntegerDigits to 3, it doesn't work as I'd like. For example, if I press 4, 5 and 3, the textview shows 453. That's fine. However, if I then press another number, for example 7, it shows 537. If I press 8 after that, it shows 378, and so on.
The same problem doesn't exist for decimal numbers. So, my question is, how can I set the actual integer limit so that when I press a number for the fourth time, the application wouldn't change the number in textview?
The code:
public class MainActivity extends AppCompatActivity {
private TextView textResult;
private TextView textSubtractor;
private TextView textSubtractee;
private String display = "0";
private String result = "0";
private SharedPreferences mPrefs;
Button btnDone;
double num1, num2, sub;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textResult = (TextView) findViewById(R.id.textResult);
textSubtractor = (TextView) findViewById(R.id.textSubtractor);
textSubtractee = (TextView) findViewById(R.id.textSubtractee);
btnDone = (Button) findViewById(R.id.btnDone);
textSubtractor.setText(display);
textResult.setText(result);
mPrefs = getSharedPreferences("test", 0);
if (mPrefs != null){
display = mPrefs.getString("display", "0");
sub = mPrefs.getInt(result, 0);
}
updateScreen();
btnDone.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
}
public void onClickNumber(View v) {
if (v.getId() == R.id.btnDot && (display.equals("") || display.contains("."))) {
return;
}
if ((v.getId() == R.id.btn0 ||
v.getId() == R.id.btn1 || v.getId() == R.id.btn2 ||
v.getId() == R.id.btn3 || v.getId() == R.id.btn4 ||
v.getId() == R.id.btn5 || v.getId() == R.id.btn6 ||
v.getId() == R.id.btn7 || v.getId() == R.id.btn8 ||
v.getId() == R.id.btn9) && (display.equals("0"))) {
clear();
updateScreen();
}
Button b = (Button) v;
display += b.getText();
updateScreen();
DecimalFormat df = new DecimalFormat("##.##");
df.setRoundingMode(RoundingMode.FLOOR);
df.setMaximumIntegerDigits(3);
num1 = Double.parseDouble(display);
textSubtractor.setText(df.format(num1));
num2 = Double.parseDouble(textSubtractee.getText().toString());
sub = num1 - num2;
textResult.setText(df.format(sub));
}
public void onClickClear(View v) {
clear();
}
private void clear() {
display = "";
result = "";
textSubtractor.setText("0");
textResult.setText("0");
}
private void updateScreen() {
textSubtractor.setText(display);
}
For a simple solution, I would suggest checking the integer and decimal part of the input when new numeric button is pressed:
//Class constants
final static int INTEGER_SIZE = 3;
final static int DECIMAL_SIZE = 2;
public void buttonPressed(View v) {
if (v.getId() == R.id.btn_dot){ // Handle dot
if(!display.contains("."))
display+=".";
}else{ // Only number values reach this
if(display.equals("0")){ // Handle default zero
clear();
updateScreen();
}
if(display.contains(".")){ //If the number contains a dot, decimal length has to be checked
String[] split = display.split("\\.");
if(split.length==2 && split[1].length()==DECIMAL_SIZE)
return; // New number is not added
}else if(display.length()==INTEGER_SIZE) //Otherwise check the length of the integer (whole sting)
return; // New number is not added
// New number will be added
Button b = (Button) v;
display += b.getText();
updateScreen();
DecimalFormat df = new DecimalFormat("##.##");
df.setRoundingMode(RoundingMode.FLOOR);
num1 = Double.parseDouble(display);
textSubtractor.setText(df.format(num1));
num2 = Double.parseDouble(textSubtractee.getText().toString());
sub = num1 - num2;
textResult.setText(df.format(sub));
}
}
In the long run, you should consider giving user some feedback like disabling the buttons or showing maximum length of the number on UI.
thanks in advance for taking time to look at my Q. and anyone with the same problem i hope we get a solution...
so basicly i have an app that spins 2 coins at the same time and displays what the result is.
This method generates the first coin...
public void coinResult1(){
ImageView coin1View = (ImageView) findViewById(R.id.coin1);
Random r = new Random();
int coin1result = r.nextInt(2);
if (coin1result == 0){
coin1View.setBackgroundResource(R.drawable.coinheads);
coinresult1 = 0;
}
else if (coin1result == 1) {
coin1View.setBackgroundResource(R.drawable.cointails);
coinresult1 = 1;
}
}
and this is for the second coin
public void coinResult2(){
ImageView coin2View = (ImageView) findViewById(R.id.coin2);
Random r = new Random();
int coin2result = r.nextInt(2);
if (coin2result == 0){
coin2View.setBackgroundResource(R.drawable.coinheads);
coinresult2 = 0;
}
else if (coin2result == 1) {
coin2View.setBackgroundResource(R.drawable.cointails);
coinresult2 = 1;
}
}
this is linked to onclick() of button which check the results to a player selection
public void checkResult(){
coinResult1();
coinResult2();
coinResult = coinresult1 + coinresult2;
if (coinResult == playerSelection){
playerWins();
buttonsReset();
}
else {
playerLost();
buttonsReset();
}
}
Now the only problem i have is...
the results of both coins of 1000 presses are this...
HeadsHeads 54%
HeadsTails 2%
TailsTails 44%
of 1000000 spins was roughly the same percentages
when each coin result was counted seprately
COIN1 heads 53% tails 47%
COIN2 heads 48% tails 52%
Now my friend says their is something wrong with those odds....beacause HeadsTails wasnt a high enough percent, hes expecting it to be close to 33% each combination at random
the code seems to favour HeadsHeads and TailsTails or HeadsTails.....ive tried several times and keep getting a low % of HeadsTails
can anyone shead some light on whats going on....and what is causing HeadsTails to rarely come out?
hope to hear back soon
Your repeated instantiation of Random is ruining the statistical properties of the generator.
You need to create one instance and pass that into your functions. Better still, use a field in your class.
Please refer to this question for concerns over thread safety of the Random class:Is Random class thread safe?. It seems to suggest that you should synchronize the nextInt calls.
You should never re-create random number generator over and over again:
public void coinResult1(){
ImageView coin1View = (ImageView) findViewById(R.id.coin1);
Random r = new Random(); // <- That's the source of errors!
int coin1result = r.nextInt(2);
...
Instead, create random generator instance once and for all:
// Simplest, not thread-safe amendment
private static Random s_Gen = new Random();
...
public void coinResult1(){
ImageView coin1View = (ImageView) findViewById(R.id.coin1);
int coin1result = s_Gen.nextInt(2);
...
The cause of the misbehaviour is that when you re-create Random it often re-initializes from the same seed (which is usually current time) and so generates the same values.
You must create only one instance of Random.
private Random r;
// initialize r in onCreate or somehere else only once
protected void onCreate(Bundle savedInstanceState){
// ...
r = new Random();
}
public void coinResult1(){
ImageView coin1View = (ImageView) findViewById(R.id.coin1);
int coin1result = r.nextInt(2);
if (coin1result == 0){
coin1View.setBackgroundResource(R.drawable.coinheads);
coinresult1 = 0;
}
else if (coin1result == 1) {
coin1View.setBackgroundResource(R.drawable.cointails);
coinresult1 = 1;
}
}
public void coinResult2(){
ImageView coin2View = (ImageView) findViewById(R.id.coin2);
int coin2result = r.nextInt(2);
if (coin2result == 0){
coin2View.setBackgroundResource(R.drawable.coinheads);
coinresult2 = 0;
}
else if (coin2result == 1) {
coin2View.setBackgroundResource(R.drawable.cointails);
coinresult2 = 1;
}
}
Thanks for all suggestion and thoughts i finally achieved it by yours suggestions and it was a simple logic work to solve the problem. I want to share it if any one want to create custom Health Bar , but it is not suitable for 100 HP because then you have to write 100 IF statements,
Idea was to create simple custom Healthbar and decrease it by pressing button clicks.
This link also help me a lot.
HealthBar
Code
private TextView Message,result;
private Button play;
private float maxHP = 10;
private float currentHP = maxHP;
//private float percentHP = (float) (currentHP/maxHP);
private int user_shield;
private float healthBar;
private ImageView shieldusb1,shieldusb2,shieldusb3;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_level_one);
Initialize();
}
private void Initialize(){
user_shield = R.raw.shield_blue;
shieldusb2 = (ImageView) findViewById(R.id.shield_b2);
shieldusb1 = (ImageView) findViewById(R.id.shield_b1);
shieldusb3 = (ImageView) findViewById(R.id.shield_b3);
result = (TextView) findViewById(R.id.result);
play = (Button) findViewById(R.id.playButton);
play.setOnClickListener(new OnClickListener(){
public void onClick(View arg0){
play();
}
});
}
public void play(){
{
healthBar=0;
currentHP = (float) (currentHP - 0.5);
//currentHP -= 1;
if(currentHP <= 0) //if the player died
{
currentHP = 0; //set his HP to zero, (just in case)
Message.setText("You died! :P"); //add any extra death-code here
//update the healthBar
result.setText ("WIN POINTS");
}
updateHealthBar();
}
}
private void updateHealthBar() {
// percentHP = currentHP / maxHP;
healthBar = currentHP;
if(healthBar<9.6){
shieldusb1.setVisibility(View.GONE);
}
{
if (healthBar<=9){
shieldusb2.setVisibility(View.GONE);
}
if (healthBar<=8.6){
shieldusb3.setVisibility(View.GONE);
}
}
}
My guess, is you need to remove the else if and make it just if because if you execute first statement where <= 1, else if will never get executed.
private void updateHealthBar() {
percentHP = currentHP / maxHP; / calculating points
healthBar = percentHP;
if(healthBar<=1){ // Hiding first Image View
shieldusb1.setVisibility(View.GONE);
}
if (healthBar<=0.9){
shieldusb2.setVisibility(View.GONE); // How to Hide this Image View after button click
}
}
Your healthBar is of int type, so checking against 0.9 is the same as checking against 1.
Also, in your conditions, you're first checking:
if (healthBar <= 1)
If this condition is true, you're hiding shieldusb1, and you will never reach second condition because you have used else. What you can do is to remove else in front of second condition, but as said above, your healthBar is int, so the second condition is basically the same as the first. Change healthBar to double.
You need to adjust these conditions
if(healthBar<=1)
...
else if (healthBar<=0.9)
Even if healthBar<= 0.9 evaluates true, healthBar<=1 is also true so it will always enter the first if
You check if healthBar is <= 1, and after if is <= 0.9... But this case never verify, cause 0.9 is < 1, so it always choose the first option!
Change your first if for check values between 1 and 0.9, and it will work!
It's only logical problem. Change if/else if block for if/if.
if(healthBar<=1)
shieldusb1.setVisibility(View.GONE);
if (healthBar<=0.9)
shieldusb2.setVisibility(View.GONE);
i am trying to get my buttons to change to a diffrent pic and a dif set of laws
it is an alphabet app that i currently have working and its on the market.... i want to make it randomly change the pic and then follow the alphebet through the whole program but i cant figure out how to get the buttons to randomize so here is the basic code that i am using
package com.alphafree;
import java.util.Random;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
public class letterA extends Activity implements OnClickListener {
/** Called when the activity is first created. */
private MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int[] _26Num = new int[6];
int i, number;
Random r1 = new Random(); // Random generator
for (i = 1; i < _26Num.length; i++) { // Pick 6 Random Numbers
do {
number = (int) (r1.nextDouble() * 26);
_26Num[1] = 1;
} while (!(number != 0 && number != _26Num[1]
&& number != _26Num[2] && number != _26Num[3]
&& number != _26Num[4] && number != _26Num[5]));
_26Num[i] = number;
}
// defines the buttons
View but1 = findViewById(R.id.let1);
View but2 = findViewById(R.id.let2);
View but3 = findViewById(R.id.let3);
View but4 = findViewById(R.id.let4);
View but5 = findViewById(R.id.let5);
but1.setOnClickListener(this);
but2.setOnClickListener(this);
but3.setOnClickListener(this);
but4.setOnClickListener(this);
but5.setOnClickListener(this);
// set the random content view
int random = (int) Math.ceil(Math.random() * 5);
if (random == 1) {
setContentView(R.layout.letter1a);
} else if (random == 2) {
setContentView(R.layout.letter1a);
} else if (random == 3) {
setContentView(R.layout.letter1a);
} else if (random == 4) {
setContentView(R.layout.letter1a);
} else if (random == 5) {
setContentView(R.layout.letter1a);
}
// here is were i need to set up the buttons
if (_26Num[1] == 1) {
let1.setBackgroundResource(R.drawable.let_a);
} else if (_26Num[1] == 2) {
setContentView(R.layout.letter1a);
}
}
public void onClick(View v) {
if (mp != null)
mp.release();
switch (v.getId()) {
case R.id.let1:
mp = MediaPlayer.create(this, R.raw.correct);
{
new AlertDialog.Builder(this)
.setTitle("Y A Y!!!! Y O U R R I G H T")
.setMessage(
"Thats the letter 'A' You Chose Correct")
.setNeutralButton("Done", null).show();
startActivity(new Intent("com.alphafree.LETTERB"));
}
break;
}
mp.seekTo(0);
mp.start();
}
}
You could do it about that way:
private static final int[] num2DrawableMap = new int[] {
R.drawable.letterA,
R.drawable.letterB,
// etc
};
private static final int[] num2LayoutMap = new int[] {
R.layout.layoutA,
R.layout.layoutB,
// etc
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int[] _26Num = new int[6];
int i, number;
Random r1 = new Random(); // Random generator
for (i = 1; i < _26Num.length; i++) { // Pick 6 Random Numbers
do {
// don't you like r1.nextInt(26) ?
number = (int) (r1.nextDouble() * 26);
// always 1? why in that loop?
_26Num[1] = 1;
} while (!(number != 0 && number != _26Num[1]
&& number != _26Num[2] && number != _26Num[3]
&& number != _26Num[4] && number != _26Num[5]));
_26Num[i] = number;
}
// set the random content view
int random = r1.nextInt(num2LayoutMap.size);
setContentView(num2LayoutMap[random]);
// find the buttons
View[] buts = new View[5];
buts[0] = findViewById(R.id.let1);
buts[1] = findViewById(R.id.let2);
buts[2] = findViewById(R.id.let3);
buts[3] = findViewById(R.id.let4);
buts[4] = findViewById(R.id.let5);
for (View but : buts) {
but.setOnClickListener(this);
int drawableId = num2DrawableMap[_26Num[i]];
but.setBackgroundResource(drawableId);
}
}
But: the Buttons have to be inside every of your layout.xml files and they need to have the same id. Otherwise you don't find them. Also you need to setContentView() before you can use findViewById()
Other than setContentView every time, Can you add all at a time and keep their visibility to GONE. what ever the button you want to display just make its visibility to VISIBLE. If you want to change make the Previous to GONE and make the new one VISIBLE.