I have 10 buttons (like calculator does) displaying digits from 0 to 9.
The problem is that I want to display unique random numbers on each button every time when I press a button. How can I achieve this behavior?
My code is:
public void generate(View view) {
Random rand=new Random();
int number=rand.nextInt(10);
but2=(Button)findViewById(R.id.button5);
but3=(Button)findViewById(R.id.button6);
but4=(Button)findViewById(R.id.button7);
but5=(Button)findViewById(R.id.button8);
but6=(Button)findViewById(R.id.button9);
but7=(Button)findViewById(R.id.button10);
but8=(Button)findViewById(R.id.button11);
but9=(Button)findViewById(R.id.button12);
but0=(Button)findViewById(R.id.button13);
but1=(Button)findViewById(R.id.button);
String mynumber=String.valueOf(number);
but2.setText(a);
but3.setText(mynumber);
but4.setText(mynumber);
but5.setText(mynumber);
but6.setText(mynumber);
but7.setText(mynumber);
but8.setText(mynumber);
but9.setText(mynumber);
but0.setText(mynumber);
but1.setText(mynumber);
but2.setText(mynumber);
Yes, it is possible.
How:
find your button. Event: onCreate
add onClickListener event to your button.
Example:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.button_component = (Button) findViewById(R.id.button_component);
this.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// RANDOM YOUR NUMBER.
}
});
}
check complete answer
int randomWithRange(int min, int max){
int range = (max - min) + 1;
return (int)(Math.random() * range) + min;
}
Related
I'm making a clicker game , where you tap a button to increase your Energy.
When my Progressbar reaches the Maximum value, it resets and sets the maximum value to the next higher one (everything works as it should be).
But when i tap again, the Progress is increased by the old maximum value but after that it continues normally.
I dont know how to fix this
public class MainActivity extends AppCompatActivity {
public int MinPoints = 0;
public int MaxPointsSSJ = 10;
public int MaxPointsSSJ2 = 20;
public int MaxPointsSSJ3 = 50;
public int Progress;
private void checker(int currentPoints, int maxPoints, int
newmaxPoints, ImageView anzeige, int bild, ProgressBar pb){
if (currentPoints == maxPoints)
maxPoints = newmaxPoints;
pb.setMax(newmaxPoints);
anzeige.setImageResource(bild);
pb.setProgress(currentPoints - maxPoints);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView Anzeige = (ImageView) findViewById(R.id.imageView);
final ProgressBar KiAnzeige = (ProgressBar) findViewById (R.id.progressBar);
Button MehrEnergie = (Button) findViewById(R.id.button);
KiAnzeige.setMax(MaxPointsSSJ);
KiAnzeige.setMin(MinPoints);
KiAnzeige.setProgress(0);
Progress = KiAnzeige.getProgress();
MehrEnergie.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Progress++;
KiAnzeige.setProgress(Progress);
if (Progress == MaxPointsSSJ){
checker(Progress, MaxPointsSSJ, MaxPointsSSJ2, Anzeige, R.drawable.goku_ssj1, KiAnzeige);
}
if (Progress == MaxPointsSSJ2){
checker(Progress, MaxPointsSSJ2, MaxPointsSSJ3, Anzeige, R.drawable.goku_ssj2, KiAnzeige);
}
}
});
}
}
Set your progressbar inderminate state, So that it will show progress infinite.
KiAnzeige.setIndeterminate(true);
try this
MehrEnergie.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
++Progress;
KiAnzeige.setProgress(Progress);
if (Progress == MaxPointsSSJ){
checker(Progress, MaxPointsSSJ, MaxPointsSSJ2, Anzeige, R.drawable.goku_ssj1, KiAnzeige);
}
if (Progress == MaxPointsSSJ2){
checker(Progress, MaxPointsSSJ2, MaxPointsSSJ3, Anzeige, R.drawable.goku_ssj2, KiAnzeige);
}
}
});
Your OnClick function is incrementing your progress bars progress by 1, but in your checker function, you are setting your progress bar progress to 0, effectively because currentPoints equals maxPoints.
So in OnClick, it looks like 1/10, 2/10, 3/10, ... 10/10, and then that triggers checker, which sets it to 0/20, and then it goes back to OnClick where it continues as 11/20, 12/20, 13/20, ... etc.
You can fix this by changing your maximum to the difference between the new maximum value and the old maximum value and then setting Progress back to 0, or by accounting for the difference when setting the progress.
Or, if you want the progress bar to "widen" so that the previous clicks are still shown, but the scale of the progress bar is increased, you can just set the progress to currentPoints in the checker function.
Hi I'm working at my first bigger app in android studio "FlashCards". I would like it to work so after you click on the button the flashcard's textview changes its text to next random flashcard untill you see all of the them how can i do something like 'continue' to my loop from inside onClick method.
here's the loop's code:
while(i < mTestDeck.size()) {
// generates random number which will represent position in deck.
int random = randomGenerator.nextInt() % mTestDeck.size();
// if random flashcard was already shown create random number again
if (mTestDeck.get(random).wasShown())
continue;
//text view that we will operate on
TextView deckTextView = (TextView) findViewById(R.id.flashcard_text_view);
// set text
deckTextView.setText(mTestDeck.get(random).getFront());
// set mWasShown to true
mTestDeck.get(random).flashcardShown();
Button myButton = (Button) findViewById(R.id.know_answer);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mTestDeck.correctAnswer();
}
});
myButton = (Button) findViewById(R.id.dont_know_answer);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
}
First, this way, you have a potential infinite loop. And if it can happens, it will happens! It's not a good idea to "get random item and check if it's ok or try again".
I think that it's better to keep a list with all items in a random order. You just have to iterate over it.
Something like:
int currentPosition = 0;
List<Card> items = new ArrayList<Card>(mTestDeck).shuffle();
// Call this method once in onCreate or anywhere you initialize the UI
private void function setCurrentCard() {
Card currentItem = items.get(currentPosition);
[...] // Set all UI views here
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (currentPosition > items.size) {
// TODO? End?
return;
}
currentPosition++;
setCurrentCard();
}
});
}
I'm trying to press the first button just one time. This button usually return a random card but I want it just one time. Then the button should be inactive. How can I do that?
That's my code:
public class GameActivity extends Activity {
Boolean buttonPressed = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
final Button background = (Button) findViewById(R.id.A);
Resources res = getResources();
final TypedArray Deck = res.obtainTypedArray(R.array.Deck);
final Random random = new Random();
if (!buttonPressed){
buttonPressed = true;
background.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
//Genrate a random index in the range
int randomInt = random.nextInt(Deck.length()-1);
// Generate the drawableID from the randomInt
int drawableID = Deck.getResourceId(randomInt, -1);
background.setBackgroundResource(drawableID);
}
});
you can disable your button with (place it inside your onClick)
background.setEnabled(false);
and you also might initialize your button to true in onCreate method
If the player has an action to do next, the simpler way is to deactivate the button when is pressed first time and after in the next action activated again.
You can do this adding
background.setEnabled(false);
in your anonymous class listener and after add
background.setEnabled(true);
in player's next action.
I know this is a simpleton question, but I am not going to school for java, just learning it online.
how to a have a textview with an initial value of 0. and then everytime you press a button it ads 25 points to the score board.
At first I wanted the button press to add a random number between 42-57 to the score board.
And then how to do convert that int or long to a string to make it fit into a textview and keep the current score, and then add a new score.
EDIT: ok so someone said I should post the code so here it is.. where do i put this..
TextView txv182 = (TextView) findViewById(R.id.welcome);
txv182.setText(toString(finalScore));
Because when I do it, I get an error: The method toString() in the type Object is not applicable for the arguments (int)
public class MainActivity extends Activity {
// Create the Chartboost object
private Chartboost cb;
MediaPlayer mp = new MediaPlayer();
SoundPool sp;
int counter;
int db1 = 0;
Button bdub1;
TextView txv182;
int finalScore;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txv182 = (TextView) findViewById(R.id.welcome);
finalScore = 100;
sp = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
db1 = sp.load(this, R.raw.snd1, 1);
bdub1 = (Button) findViewById(R.id.b4DUB1);
bdub1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (db1 != 0)
sp.play(db1, 1, 1, 0, 0, 1);
txv182.setText(finalScore);
}
});
First you need to store your score to certain integer variable say score and set it to any initial value you want and use.
TextView tv = (TextView) findViewById(R.id.myTextView);
tv.setText(toString(score));
you do not need to initialize the textview with value just in onclick() of button do score+=25and add text to your textview as above.
hope this helps
It's actually like this..
pernts+=25;
txv182.setText(String.valueOf(pernts));
in android, after the
public class MainActivity extends Activity {
but before..
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
i wrote..
int pernts;
String strI;
so then after the above #Override majigy, i wrote..
strI = "" + pernts;
pernts = 0;
because when i wrote it like.. int pernts = 0; it never worked, forcing me to add final and what not..
any way.. How to convert an integer value to string? anSwered the question..
and so the end was like this
pernts+=25;
txv182.setText(String.valueOf(pernts));
i figured out you have to add a value to the int variable not the string.. i kept wanting to add 25 and i was getting 25252525252525.., instead of 25 50 75 100.. kinda cool actually.. separating the logic of how to "add" 25 .. anyway thanks.. SOF!
30 minutes later... found this.. How can I generate random number in specific range in Android?
..
import android.app.Activity;
public class InsMenu extends Activity {
static TextView txv182;
static int pernts;
Button bdub1;
public static void addPernts() {
int min = 37;
int max = 77;
Random r = new Random();
int i1 = r.nextInt(max - min + 1) + min;
pernts+=i1;
txv182.setText(String.valueOf(pernts));
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.BLAHBLAH);
bdub1 = (Button) findViewById(R.id.b4DUB1);
txv182 = (TextView) findViewById(R.id.welcome);
bdub1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
addPernts();
}
--- i created my first objekt thanks to this too.. http://www.tutorialspoint.com/java/java_methods.htm ..
i've made a simple counter program, where i click the plus or minus button and it adds or removes 1 from a counter.
I would like to be able to add more counters: ex. counter1, counter2, counter3 etc.
Here's an example of how i'm doing now with 2 counters, but as you can see i have declared my variables, and i would like to generate them automaticly
int counter, counter2;
ImageButton add, sub, add2, sub2, btnSet;
TextView display, display2;
And here's how i am using the plus button
// Plus button setup
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
counter++;
display.setText(""+counter);
Vibrator vibr = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibr.vibrate (20);
You could create a class that holds the information related to your increment button:
class IncrementButton {
int step;
int counter;
ImageButton add, sub;
TextView display;
public IncrementButton(int step) {
this.step = step;
add = ...
sub = ...
display = ...
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
counter += step;
display.setText("" + counter);
Vibrator vibr = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibr.vibrate (20);
}
}
...
}
}
and put objects of that class in a list - for example for 3 buttons:
List<IncrementButton> buttons = new ArrayList<IncrementButton> ();
for (int i = 0; i < 3; i++) {
IncrementButton btn = new IncrementButton(i + 1);
buttons.add(btn);
}
Create your won widget that contains counter, 2 buttons (for add and subscribe) and text view,
put all you logic there (on click listener etc...), and just hold list of how-many-instances-that-you-want in your activity.