I'm a newbie android programmer.
I'm tring to create a simple game.
Game;
Displaying a random number bettween 1 to 10, let's say it mainnumber.
Displaying 4 buttons.
First button value is mainnumber.
Second button value is mainnumber + 1
Third button value is mainnumber - 1
and The Last button value is mainnumber + 2
How to play;
If the user clicked correct button (mainnumber), it'll display another number and buttons.
My Code;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_easygame);
Button b1 = (Button)findViewById(R.id.answer_one);
Button b2 = (Button)findViewById(R.id.answer_two);
Button b3 = (Button)findViewById(R.id.answer_three);
Button b4 = (Button)findViewById(R.id.answer_four);
Random number = new Random();
int mainnumber = number.nextInt(10)+1;
int rnd1 = mainnumber + 1;
int rnd2 = mainnumber + 2;
int rnd3 = mainnumber - 1;
String a = Integer.toString(mainnumber);
String b = Integer.toString(rnd1);
String c = Integer.toString(rnd2);
String d = Integer.toString(rnd3);
((TextView) findViewById(R.id.display)).setText(Integer.toString(mainnumber));
List<Button> buttons = Arrays.asList(b1, b2, b3, b4);
List<String> texts = Arrays.asList(a, b, c, d);
Random rand = new Random();
buttons.get(rand.nextInt()).setText(texts.get(rand.nextInt()));
}
Getting system error, and app closing.
Question;
How can I display buttons randomly each time, and how can I check the clicked button is true button.
Thanks...
Collections.shuffle(texts);//shuffle the buttons
//shuffle the buttons if you want as well, but whatever..
int i = 0;
//for loop moved below..
/*
for(Button button : buttons)
{
button.setText(texts.get(i++));
}
*/
//custom android.view.View.OnClickListener instance.
OnClickListener onClick = new OnClickListener()
{
public void onClick(View view)
{
Button button = (Button) view;//safe cast since this is only added to buttons.
String value = button.getText();
//process button value..
}
};
for(Button button : buttons)
{
button.setText(texts.get(i++));
button.setOnClickListener(onClick);
}
Related
I am trying to make 2 different view for user that is one for recommendation i.e (to show one single button) and another for just all information. I need the app to call a random button among all the other button every time i restart the app.
In my opinion, what is better is to have a single button and every time you restart the app you pick a random behaviour for that button.
There are several ways to do it this is just one:
public class MainActivity extends AppCompatActivity {
private static final String BUTTON_TEXT1 = "Button 1";
private static final String BUTTON_TEXT2 = "Button 2";
private static final String TEXTVIEW_TEXT1 = "Text to display #1";
private static final String TEXTVIEW_TEXT2 = "Text to display #2";
private String[] mButtonTexts = {BUTTON_TEXT1, BUTTON_TEXT2};
private String[] mTextViewTexts = {TEXTVIEW_TEXT1, TEXTVIEW_TEXT2};
private static final int NUM_OF_TEXT = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
final TextView textView = (TextView) findViewById(R.id.textView);
Random random = new Random();
final int index = random.nextInt(NUM_OF_TEXT);
button.setText(mButtonTexts[index]);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(mTextViewTexts[index]);
}
});
}
}
As per #MarkPazon suggestion
1. Assign a Button(the random One )
2. Declare a function callRandom()
3. invoke the function callRandom() from Onclick event of the Random
Button
public void callRandom(){
//Generate Random Numbers
final int min = 0;
final int max = n; //n-no of random events
Random g=new Random();
final int random = g.nextInt((max - min) + 1) + min;
//Random number 0(inclusive)-9(inclusive)
switch(random){
case 1:
//Function 1 break;
case 2:
//Function 2 break;
case 3:
//Function 3 break;
case n:
//Function n break;
}
}
PS: Here The function calls a Random event on every Button Click.If You Wish to assign random function at the Time of App Starts then paste this with in Oncreate
//Generate Random Numbers
final int min = 0;
final int max = n; //n-no of random events
Random g=new Random();
final int random = g.nextInt((max - min) + 1) + min;
//Random number 0(inclusive)-9(inclusive)
my project contains the grid view in which i created the custom view. Custom view had minus button, text view and plus button. My intention is like that, when i press on minus or plus button, the value of text view get changes according to some point. Please tell me how to implement that.
Thanks in advance.
String number = mTextView.getText()
int numberInt = Integer.parseInt(number);
IN plus button onClickListener
numberInt++
IN minus button onClickListener
numberInt--
and final
mTextView.setText(""+numberInt);
TextView mCount = (TextView) findViewById(R.id.count);
Button plus = (Button) findViewById(R.id.plus);
Button minus = (Button) findViewById(R.id.minus);
plus.setOnClickListener(onClickListener);
minus.setOnClickListener(onClickListener);
private final View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.minus:
mCount.setText(String.valueOf(Double.valueOf(mCount.getText().toString()) - 1));
return;
case R.id.plus:
mCount.setText(String.valueOf(Double.valueOf(mCount.getText().toString()) + 1));
return;
default:
}
}
};
You can set OnClickListener on button inside your gridView adapter, like this:
button.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
String data = mTextView.getText().toString();
double number = Double.parseDouble( data );
number++; //if you want to increase it by 1
//or
number += someValue; //if you want to increase it by some value
mTextView.settext(String.valueOf( number ));
}
} );
similarly you can set click listener on another button to subtract the value, just replce
number++;
//or
number += someValue;
with
number--;
//or
number -= someValue;
Every time an user click on the button it has to show "John - Sue" or "Sue - John".
I tried with this code:
public class MyActivity extends Activity {
ArrayList<String> names = new ArrayList<String>();
int p1, p2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myactivity);
names.add("John");
names.add("Sue");
Button b = (Button) findViewById(R.id.mybutton);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
p1 = (int)Math.random();
if (p1 == 0)
p2 = 1;
else
p2 = 0;
String msg = names.get(p1) + " - " + names.get(p2);
AlertDialog msgbox = new AlertDialog.Builder(About.this).setTitle("Click here").setMessage(msg).create();
//msgbox.setPositiveButton("OK", null);
msgbox.setCancelable(true);
msgbox.show();
TextView textView = (TextView) msgbox.findViewById(android.R.id.message);
textView.setTextSize(16);
}
});
}
}
But i get always the same order, even i close and run again the app. How to do that?
If you want shuffle list:
Collections.shuffle(names)
If you want random int between 0 or 1 (nextInt(int) javadoc):
Random random = new Random();
int randomInt = random.nextInt(2);
Math.random() returns a number between 0 and 1. So when you cast it to int it will always be 0.
Try this:
p1 = (int)(Math.random()*2);
It happens because
p1 = (int)Math.random();
always gives you zero.
In an android app I intend to allow users to answer a random sum then a new one appears on screen. This is repeated 10 times and then a final score will then be given. However I am unsure how to update the sum so that after each each a new random is shown on screen.
Below is my current code:
public class Test extends Activity {
//declare vars
TextView text;
EditText answer;
Button submit;
int random1;
int random2;
String question;
int correctAnswer;#
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
// initialising variables
initialiseVars();
//set up random
setUpRandom();
//Set text view equal to question
text.setText(question);
//updateQuestion?
}
public void initialiseVars() {
text = (TextView) findViewById(R.id.tvTopRandomTest);
answer = (EditText) findViewById(R.id.etEnterAnswerRandomTest);
submit = (Button) findViewById(R.id.btnSubmitRandomTest);
}
public void setUpRandom() {
//setting up randoms
Random random = new Random();
// Generating random number between 1 and 12
random1 = random.nextInt(12) + 1;
// Generating another random number between 1 and 12
random2 = random.nextInt(12) + 1;
question = random1 + " x " + random2 + " = ";
correctAnswer = random1 * random2;
}
public void updateQuestion() {
//CODE TO UPDATE QUESTION
}
}
Add Button ClickListener so that when user press submit button it will update question and clean all previous values
submit = (Button) findViewById(R.id.btnSubmitRandomTest);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
updateQuestion();
}
}
Maintain a count in your activity and increase it in updateQuestion
public void updateQuestion() {
if (Int.parseString(answer.getText().toString()) != correctAnswer) {
// Show toast or something
return;
}
tries++;
if (tries == 10) return; // or do something else;
answer.setText("");
setUpRandom();
text.setText(question); // add this line in your setUpRandom();
}
To generate random integers look at this. Hopefully this will help you out.
I am making an application in which i have to fetch item name and price from first activity to another and i am able to do that but in second activity i am allowing user to put quantity in numbers and whenever user will click on button a TextView to show total amount, but not able to calculate total Amount for item.
I know this is very simple task to do but i am getting error while write this line in button onClick():
txtResult=txtCost*txtQty
here i am placing second activity code,
please correct this one:-
public class SecondScreenActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen2);
TextView txtName = (TextView) findViewById(R.id.txtName);
TextView txtCost = (TextView) findViewById(R.id.txtCost);
EditText txtQty=(EditText)findViewById(R.id.txtQty);
Button btnClose = (Button) findViewById(R.id.btnCalculate);
TextView txtResult = (TextView) findViewById(R.id.txtResult);
Intent i = getIntent();
// Receiving the Data
String name = i.getStringExtra("name");
String cost = i.getStringExtra("cost");
// Displaying Received data
txtName.setText(name);
txtCost.setText(cost);
// Binding Click event to Button
btnClose.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//Closing SecondScreen Activity
//finish();
txtResult=txtCost*txtQty;
}
});
}
}
You can do it by
int cost = Integer.parseInt(txtCost.getText().toString());
int qty = Integer.parseInt(txtQty.getText().toString());
int result = cost*qty;
and then set this result into txtResult
txtResult.setText(result+"");
or you can convert int to String and then apply setText
Why are to multiplying value in Textview
btnClose.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Float f_name = new Float(name);
Float f_cost = new Float(cost);
Float f_result=f_name *f_cost ;
txtResult.setText(f_result);
}
});
}
}
txtResult=txtCost*txtQty;
These are TextView objects. You can't do maths on objects. Get the textview's values into integers and then try to multiply.
Do something like this.. depending on the type of variable you want (integer, float, double).
int a = new Integer(txtCost.getText().toString());
int b = new Integer(txtQty.getText().toString());
int c = a * b;
txtResult.setText(d);
There are 2 changes that needs to be made.
Make both txtCost and txtQty global variables.
both these variables cannot be directly multiplied. Instead do somthing like this.
double cost = Double.parseDouble(txtCost.getText().toString());
double qty = Double.parseDouble(txtQty.getText().toString());
txtResult = cost * qty ;