How do I create a custom toast message that displays random messages - java

xml for the button:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button001"
android:text="#string/text_7"
android:textStyle="bold"
android:layout_gravity="center"/>
I want to display messages ("Hello", "Bonjour", "Good day", "Lets Go") as toasts randomly.
The java code for the toast function:
Button button001;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
button001 = (Button) findViewById(R.id.kabutton);
button001.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String[] {"Hello","Bonjour!","Good day","Lets Go"};
Toast.makeText(getApplicationContext(),[String],Toast.LENGTH_LONG);
}
});
}
}

You can create your string array and then get a random index every time you click the button.
#Override
public void onClick(View v) {
String[] randomStrings = new String[] {"Hello","Bonjour!","Good day","Lets Go"};
Toast.makeText(getApplicationContext(),randomStrings[new Random().nextInt(randomStrings.length - 1)],Toast.LENGTH_LONG).show();
}

You can create custom view for the Toast message using setView() method. Check this.
For the random, you Java's Random class nextInt() method and have those strings as list and using the int that random gave you to access one at a time.

Related

Is there a Java command that means "if any button is pressed"?

I'm trying to work on some code I did for a dice rolling app, where if the roll button was pressed it would display random dice sides.
I am trying to re-use this concept for my multiple choice quiz app, where if any button is pressed, right, or wrong, it will move on to the next question:
I was thinking it would look something like this, with "button" representing all buttons being pressed.
However in this multiple choice quiz there will only be 4 buttons (A, B, C and D) that I want to have cause this happen if pressed. I'm sure I could make this happen by repeating the paragraph of code 4 times with each button, but I was wondering if there was a simpler way to have all 4 buttons be represented on the same line
(A lot of the code I'm showing is meant to be for a dice app it's mainly the first word of the first line I want help with)
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("multic", "the Button has been pressed!");
Random randomNumberGenerator = new Random();
int number = randomNumberGenerator.nextInt(8);
Log.d("Dicee", "the random number is: " + number);
leftDice.setImageResource(diceArray[number]);
int number1 = randomNumberGenerator.nextInt(8);
rightDice.setImageResource(diceArray[number1]);
}
});
I expect that after one of the buttons is pressed it will move on to the next question.
You can define the listener like this:
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("multic", "the Button has been pressed!");
Random randomNumberGenerator = new Random();
int number = randomNumberGenerator.nextInt(8);
Log.d("Dicee", "the random number is: " + number);
leftDice.setImageResource(diceArray[number]);
int number1 = randomNumberGenerator.nextInt(8);
rightDice.setImageResource(diceArray[number1]);
}
};
and then set it to as many buttons as you want:
button1.setOnClickListener(listener);
button2.setOnClickListener(listener);
button3.setOnClickListener(listener);
button4.setOnClickListener(listener);
You can use a single listener object with a switch statement to check which button is clicked.
Button b1,b2;
//findViews
View.OnClickListener listener=new View.OnClickListener() {
#Override
public void onClick(View v) {
//code
switch((Button)v){
case b1:
//code
break;
case b2:
//code
break;
}
//code
}
};
b1.setOnClickListener(listener);
b2.setOnClickListener(listener);
For a multiple choice quiz, with a set of 4 possible answers, I would suggest that you use a RadioGroup with constituent RadioButtom objects, like so:
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton android:id="#+id/radio_pirates"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/pirates"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="#+id/radio_ninjas"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/ninjas"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
Notice how each RadioButton has the onClick attribute. You can name the same method for all radio buttons, and then in the activity or fragment use one method for all buttons with a switch statement, like so:
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radio_pirates:
if (checked)
// Pirates are the best
break;
case R.id.radio_ninjas:
if (checked)
// Ninjas rule
break;
}
}
To read more: https://developer.android.com/guide/topics/ui/controls/radiobutton#java
Multiple different choices as i am thinking it:
1)
Set android:onClick="onNextQuestion" on xml of all your buttons.
then in your java code write:
public void onNextQuestion(View view) {
// Do something in response to button click
}
2) (Better as can work in more cases) Make an NextQuestionClickListener class which will implement the interface View.OnClickListener and will implement the method onClick doing the code you wish.
class NextQuestionClickListener implements View.OnClickListener {
#Override
public void onClick(View v) {
// Do something in response to button click
}
}
Then set the listener to each button:
NextQuestionClickListener nextQuestionClickListener = new NextQuestionClickListener();
Button button1 = (Button) findViewById(R.id.button1);
Button button2 = (Button) findViewById(R.id.button2);
...
button1.setOnClickListener(nextQuestionClickListener);
button2.setOnClickListener(nextQuestionClickListener);
...
3) Using RxJava and RxBindings
RxView.clicks(button1)
.mergeWith(RxView.clicks(button2))
.mergeWith(RxView.clicks(button3))
.mergeWith(RxView.clicks(button4))
.subscribe(aVoid -> {
// Do something in response to button click
}, throwable -> Log.e(TAG, "error in handling click of next question", throwable));
4) Also i found butterknife where you can do:
#Onclick({R.id.button1,R.id.button2,R.id.button3,R.id.button4})
void onButtonClick(View aView) {
// Do something in response to button click
}

How do I click on a button that makes an invisible button appear in android? [duplicate]

This question already has answers here:
how to show/hide layout on button click
(5 answers)
Closed 5 years ago.
I need to do a quiz with levels and I would like the next level button to appear only when a certain button was clicked, how to do it? (Please be detailed, because I'm new to java)
This should be in your java code:
certain_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
button_next_level.setVisibility(View.Visible);
}
});
In your xml layout file, make the button_to_appear as gone.
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button_next_level"
android:visibility="gone"
/>
Activity A:
btnA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ActivityA.this, ActivityB.class);
i.putExtra("isAnswerCorrect",true);
startActivity(i);
}
});
Activity B:
...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_b);
boolean isAnswerCorrect = getIntent().getBooleanExtra("isAnswerCorrect", false);
if (isAnswerCorrect) {
next_level_btn.setVisibility(View.VISIBLE);
} else {
next_level_btn.setVisibility(View.GONE);
}
}
...
In this case, Activity A is where you are pressing the button and Activity B is the activity you are showing your next level button on,

how to use java onclick shuffle array

I am learning how to use strings and onlclick in java. I have written a programme below which shuffle three names and then outputs them into three buttons.
When I click on Paul, I want the message to be displayed in message box. Since Paul will be in a button each time. I am puzzled on how to attach my message to Paul.
Paul moves around due to the use of array. I understand this is a tough question, but I also know, there are some very clever ppl out there who love a challenge.
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void generate(View view) {
String [] names = new String[3];
names[0] = "Bob";
names[1] = "Paul";
names[2] = "Mike";
Button btn_a = (Button) findViewById(R.id.a);
Button btn_b = (Button) findViewById(R.id.b);
Button btn_c = (Button) findViewById(R.id.c);
TextView message = (TextView)findViewById(R.id.message);
Arrays.asList(names);
Collections.shuffle(Arrays.asList(names));
btn_a.setText(names[0]);
btn_b.setText(names[1]);
btn_c.setText(names[2]);
}
public void a1(View view) {
}
public void b1(View view) {
}
public void c1(View view) {
}
}
This is a trick practical implementation in Java where a single listener is used for multiple buttons, rather than one listener for each button, so that each button's content determines what happens, not each button's listener. Helps for dynamic button grids (i.e. an 8x8 chessboard) to not define 64 listeners and code them all.
I don't have an Android IDE on hand, so this is pseudo-code, but you should be able to get the gist from this.
//Create a Universal Listener for all our buttons
OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
Button b = (Button)v;
String text = b.getText().toString(); //get the button's name
if(text.equals("Paul")) {
//do anything for Paul ONLY in here
}
}
});
btn_a.setOnClickListener(listener); //give all the buttons the same listener, but only Paul's listener will do anything when you click on it
btn_b.setOnClickListener(listener);
btn_c.setOnClickListener(listener);
Using info from: http://developer.android.com/reference/android/widget/Button.html and https://stackoverflow.com/a/5620816/2958086

Onclick listener throwing NullPointerException

I've setup a button and I'm trying to display a toast when the user clicks on it. Here's my Java code -
file = (Button) findViewById(R.id.file);
file.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Display the file chooser dialog
//showChooser();
Toast.makeText(getApplicationContext(), "this is my Toast message!!! =)", Toast.LENGTH_LONG).show();
}
});
Here's my XML code to setup the button -
<Button
android:id="#+id/file"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/plt"
android:text="File" />
This throws a NullPointerException on the line file.setOnClickListener(new OnClickListener() { . What am I doing wrong?
Are you initializing the Button inside the onCreate() method of your Activity?
If so, please check if you are calling
setContentView(R.id.yourlayoutfile);
before initializing the Button with findViewById(R.id.file);
Your error occurs because your Button "file" is null, which means that findViewById(...) didn't find any View with that id. The reason therefore can either be that there is no such ID in the inflated layout, or that you didn't call setContentView(...)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yourlayoutfile);
// initialize your button here
}
try to clean project
project-->clean-->choose your project-->ok,
then run again.
if you still facing the same problem you can use another way to set click action
in your XML
<Button
android:id="#+id/file"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/plt"
<!--added line-->
android:onClick="anyName"
android:text="File" />
and then in you activity remove the initialization of the button and click listner too
and make the code looks like that
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.id.yourlayoutfile);
}
public void anyName(View v){
Toast.makeText(getApplicationContext(), "this is my Toast message!!! =)",
Toast.LENGTH_LONG).show();
}
Hope this help.
If there is a Null pointer exception on this line:
file.setOnClickListener(new OnClickListener()
then it mean your file object is null
Make sure you initialize your file object before adding a listener to it.

Hello World Multiple Buttons Separate Actions

I'm new to android development, and haven't programmed GUI's in java yet so button work is all new to me.
I'm making a simple hello world app, has some buttons/radios/checkboxes etc. We have to figure out a way to make it nice, there is nothing specific in the brief. so I figured I'd get some buttons and show the different kinds of toast, maybe change the background etc.
so I implemented a toast based off a tutorial, but it works on all of the instantiated buttons instead of just the one I want. I would like the other button to do something else.
I think it has to do with the onClickListener, but beyond that I'm stuck.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn1 = (Button) findViewById(R.id.button1);
btn1.setOnClickListener(this);
btn2 = (Button) findViewById(R.id.button2);
btn2.setOnClickListener(this);
cb=(CheckBox)findViewById(R.id.check);
cb.setOnCheckedChangeListener(this);
browser=(WebView)findViewById(R.id.webkit);
browser.loadUrl("http://www.google.com/search");
}
public void onClick(View v) {
new AlertDialog.Builder(this).setTitle("MessageDemo").setMessage(
"This is an Alert Dialogue Toast").setNeutralButton(
"Here, here!", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dlg, int sumthin) {
Toast.makeText(HelloWorldActivity.this,
"<clink, clink>", Toast.LENGTH_SHORT).show();
}
}).show();
}
and here's the xml for the buttons
<Button android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Testa"
android:layout_weight="0.2"></Button>
You've added the same onClickListener to each button so they will have the same behavior. You can actually create the listener right inside the setOnClickListener call, like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn1 = (Button) findViewById(R.id.button1);
btn1.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
new AlertDialog.Builder(this).setTitle("MessageDemo").setMessage(
"This is an Alert Dialogue Toast").setNeutralButton(
"Here, here!", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dlg, int sumthin) {
Toast.makeText(HelloWorldActivity.this,
"<clink, clink>", Toast.LENGTH_SHORT).show();
}
}).show();
}
});
btn2 = (Button) findViewById(R.id.button2);
btn2.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
// Do something different here.
}
});
// The rest of onCreate
}
EDIT: I've updated the answer to make it clear which parts of your original code would go where, but I usually wouldn't stick a big chunk of code like that inside of the onClick as it's not very readable. I'd prefer something more like this:
public void onCreate(Bundle savedInstanceState) {
// other onCreate code
btn1 = (Button) findViewById(R.id.button1);
btn1.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
showBtn1ClickedDialog();
}
});
// other onCreate code
}
private void showBtn1ClickedDialog() {
new AlertDialog.Builder(this).setTitle("MessageDemo").setMessage(
"This is an Alert Dialogue Toast").setNeutralButton(
"Here, here!", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dlg, int sumthin) {
Toast.makeText(HelloWorldActivity.this,"<clink, clink>", Toast.LENGTH_SHORT).show();
}
}).show();
}
In addition to goto10's solution, if you're not interested in defining the listeners in-line, your existing click handler can check the ID of the view:
public void onClick(View view) {
switch (view.getId()) {
case R.id.about_button:
// handle about
break;
// etc.
I tend towards goto10's solution, or even inner classes, rather than a switch statement like this, but it's another option. That said, I'm voting up his/her answer, and not mine.
One reason to use a switch instead of inner classes is memory usage, although with modern devices, this might not be a huge issue--but each inner class does take more space, and if the handler is small, IMO is more efficient to do it this way.
Clicking on any button generates an event which is caught by the onClick eventListener. But it doesn't automatically distinguish between the events as to which click generated the event. The information is contained in the View v and by using a switch case on the view, we can have separate events for different clicks.
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btn1:
//Do something here
break;
case R.id.btn2:
//Do something else here
break;
case R.id.btn3:
break;
}
}
A summary of how you can use Listeners in your application.

Categories

Resources