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
}
Related
I have two different edittext fields, each with a 'clear' button to clear the inputted text. I can clear both fields like so:
XML:
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/fieldOneInput"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/clearButtonText"
android:id="#+id/clearTextField1"
android:onClick="clearTextField1"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/fieldTwoInput"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/clearButtonText"
android:id="#+id/clearTextField2"
android:onClick="clearTextField2"/>
Java:
public void clearTextField1(View view){
EditText fieldOneInput = (EditText) findViewById(R.id.fieldOneInput);
fieldOneInput.setText("");
}
public void clearTextField2(View view){
EditText fieldTwoInput = (EditText) findViewById(R.id.fieldTwoInput);
fieldOneInput.setText("");
}
This isn't practical if I have multiple edittexts each with a 'clear' button. How would I go about clearing different edittexts fields using different buttons while reusing the same (java) code?
You can achieve this using following code:
public class AbcActivity extends Activity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//... your code here, to get button objects from xml file
button1.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
button4.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.button1:
clearEditText(R.id.editText1);
break;
case R.id.button2:
clearEditText(R.id.editText2);
break;
case R.id.button3:
clearEditText(R.id.editText3);
break;
case R.id.button4:
clearEditText(R.id.editText4);
break;
}
}
private void clearEditText(int editTextId) {
findViewById(editTextId).setText("");
}
}
You can define a method like this:
private void setClickListener(Button button, final EditText editText) {
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
editText.setText("");
}
});
}
And then you can call
setClickListener(button1, editText1);
setClickListener(button2, editText2);
...
Note: Avoid calling findViewById(id) inside onClickListener, do it just one time before setting the listener.
Use this for every text field
public void clearTextField1(EditText editText){
editText.setText("");
}
You can use following code snipset to make code reusable
You have to call this method on button click. And pass edittext which you wants to clear and button on which you wants to clear edittext
public void clearOnClick(final EditText edtClear, Button btnClear)
{
btnClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
edtClear.setText("");
}
});
}
Well either way you still have to instantiate the buttons, this is obvious. One way that I can recycle my code and make it easy is I copy and paste a stock code, such as
public void clearTextField*(View view){
EditText* fieldOneInput = (EditText) findViewById(R.id.fieldOneInput*);
fieldOneInput*.setText("");
}
And then proceed to use Notepad++ (specifically the find and replace function to replace the "*" with whatever number textView you are on. Simple and effective. Besides this I suppose you could create a public void function similar to this and pass the id of the button into it like so:
public void ClearText(String id){
Button defaultButton = (Button)findViewById(id);
defaultbutton.setText("your text");
}
But I didn't test that code so don't fault me if there is an error or exception in there. Hope this helps!
First of all, whenever you feel like you need more than one click listeners for buttons,etc. in your class, just implement the interface View.OnClickListener.
Each view has a unique id that we assign to it. These ids are stored as compile time constants and hence can be referenced into a switch case.
Note: This approach does'nt work if you want to your code to be added as a module.
You can use answer by naran z and modify it a little.
#Override
public void onClick(View view) {
int id = INVALID_EDITTEXT_ID; // say -1
switch (view.getId()) {
case R.id.button1:
id = R.id.editText1;
break;
case R.id.button2:
id = R.id.editText2;
break;
case R.id.button3:
id = R.id.editText3;
break;
case R.id.button4:
id = R.id.editText4);
break;
}
if(id!=INVALID_EDITTEXT_ID)
findViewById(id).setText("");
}
I have a tic tac toe app, and I want to know whether it is possible to set all the tic tac toe buttons to one on_click event, and then create a variable to get the ID of the button clicked, then pass it as a parameter to another method which will do the actual functionality, OR do I need to create different on_click events for each button?
You can do something like this, and add as many "cases" as needed:
View.OnClickListener sharedClickHandler = new View.OnClickListener() {
public void onClick(View view) {
switch(view.getId()) {
case R.id.button1:
// handle first button
break;
case R.id.button2:
// handle second button
break;
}
}
}
You can just use one listener - the onClick method takes a View parameter, which is the view that was clicked on. You can then find out which of your buttons that was:
View.OnClickListener sharedClickHandler = new View.OnClickListener() {
public void onClick(View view) {
int id = view.getId();
// Do the right thing based on the ID
}
}
Exactly how you do what you need to do based on the ID is up to you. For simple examples you could just use a switch/case statement; in other cases if you're mapping from ID to something else (a mutable object representing game state for example) you could use a Map<Integer, GameObject> and just get the right one...
hello you can use the same click event for button, you can attach for example an integer as a tag to the button so that you can know which button was clicked and handle accordingly.
button1.setTag(1);
button2.setTag(2);
button3.setTag(3);
button1.setOnClickListener(buttonClick());
button2.setOnClickListener(buttonClick());
button3.setOnClickListener(buttonClick());
public View.OnClickListener buttonClick(){
View.OnClickListener click = new View.OnClickListener() {
#Override
public void onClick(View v) {
int numberClicked = v.getTag();
//You have now the button clicked
}
};
return click;
}
I am new to android programming and so please pardon if the question looks stupid.
I am creating a Calculator in Android and for the user interface I have many buttons (around 20 for 10 digits, and various operation). Now there is a string expression that I calculate once the user presses the button "=". However if he presses any other button then the input is updated. Say he presses "1" then input =1; then he presses 2 then input becomes "12" and so on.
So I need to call the same function whenever various buttons are pressed, but the input to the function is different.
I can go-by this by making n different functions, one for each button but that is not very scalable.
So how can I go about it?
The current xml file is:
<Button
android:id="#+id/Button01"
android:layout_width="70dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/Button03"
android:layout_alignBottom="#+id/Button03"
android:layout_toRightOf="#+id/Button03"
android:onClick="UpdateExpression_/"
android:text="/" />
<Button
android:id="#+id/Button02"
android:layout_width="70dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/Button01"
android:layout_alignBottom="#+id/Button01"
android:layout_toRightOf="#+id/Button01"
android:onClick="UpdateExpression_X"
android:text="x" />
I need to update to android:onClick="UpdateExpression" and mention some input to this function call.
Thank you.
You will need a central onClick method, let's call it updateExpression(View v) Also a note about your code: method names should start with a lowercase letter, it's a Java naming convention.
android:onClick="updateExpression"
Now the implementation:
public void updateExpression (View v)
{
switch (v.getId())
{
case R.id.button1:
//do stuff here
break;
case R.id.button2:
//do other stuff here
break;
}
}
The reason you need v.getId() is because you're checking the id of the button then doing something if it's that particular id. This logic is needed since all your buttons will implement that same method.
Here is the implementation using code....
In the onClick function, compare the v.getId() to each of your Android layout ids, like R.id.button1 R.id.button2 etc...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Here are some buttons defined in the XML layout as button1, button2, etc...
Button button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(myListener);
Button button2 = (Button)findViewById(R.id.button2);
button2.setOnClickListener(myListener);
Button button3 = (Button)findViewById(R.id.button3);
button3.setOnClickListener(myListener);
}
//Create an anonymous implementation of OnClickListener
private OnClickListener myListener = new OnClickListener() {
public void onClick(View v) {
Log.d(logtag,"onClick() called");
Toast.makeText(MainActivity.this, "The " + v.getId() + " button was clicked.", Toast.LENGTH_SHORT).show();
}
};
Forgive me if this has been asked before. I have poured through this site and many others and can't seem to find an answer. I have a working Android app but I'm trying to clean the code up. I have 3 buttons:
public Button button1, button2, button3;
Then, I have a method that "grabs" the clicks:
public void getButtonClick(View view)
{
switch(view.getId())
{
case R.id.button1:
// Do something button1 related here
break;
case R.id.button2:
// Do something button2 related here
break;
case R.id.button3:
// Do something button3 related here
}
}
What I'd like to know is if there is any way I can have a generic method that will just wait for a button click and grab that variable so that I can avoid the multiple switch-case statements. Something on the line of:
public void oneMethodForAll(View view)
{
clkdBtn = view.getButtonThatWasClicked();
// Do stuff
}
Any help is greatly appreciated. TIA
One thing you can do is to have the activity implement View.OnClickListener:
public class FooActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle icicle) {
Button btn1 = (Button) findViewById(R.id.button1);
btn1.setOnClickListener(this);
Button btn2 = (Button) findViewById(R.id.button2);
btn2.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.button1:
// Button 1 was clicked
break;
case R.id.button2:
// Button 2 was clicked
break;
}
}
}
That will save you a little bit of typing since you're not creating a bunch of anonymous click handlers, but you will still have to set the onClickListener of each button individually.
Typically you implement different handlers for different buttons since the action the button will signal is usually different.
You can cast your View to a Button by using the View which is being passed as the sole parameter into your handler.
Button clickedButton = (Button)view;
If all you care about is the id of the button and your action will be based on that value then create separate handlers.
You can just do:
clkdBtn = (Button)view;
Usually the Button itself isn't used though. getButtonClick() should respond to the button presses with their corresponding action... I'm not sure why you'd need the actual button view itself.
If you want the text that the Button is showing, you could use:
String text = ((Button)view).getText();
I wan reading here about handling UI events. I know java pretty well but still never
had the chance of writing a gui so I don't know much about listeners. Anyway, they use
a technique I have never came across before, here's what I mean
// Create an anonymous implementation of OnClickListener
private OnClickListener mCorkyListener = new OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
}
};
The first line of code confuses me: it looks like a declareation of a new object, but then
its a method? I just don't understand this code and if you can help me understand it I can continue my assignment :)
P.s. two more question: if I have several buttons on the screen, they all share the same onCLick() method? and if so, how do I know which one was clicked?
Thanks!
Hi you can write this way also
public class testActivity extends Activity implements OnClickListener {
And Add this way...
ImageButton Ibutton = (ImageButton) findViewById(R.id.button_1);
Ibutton.setOnClickListener(this);
ImageButton Ibutton2 = (ImageButton) findViewById(R.id.button_2);
Ibutton2.setOnClickListener(this);
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.button_1:
// action to preform on button 1
Toast.makeText(testActivity.this, "Button 1 pressed ", Toast.LENGTH_SHORT).show();
break;
case R.id.button_2:
// action to preform on button 1
Toast.makeText(testActivity.this, "Button 2 pressed ", Toast.LENGTH_SHORT).show();
break;
}
}
As each view is attached with separate listener you each event can recognize that it belongs to which view
use the following approach
step1 your class should implement OnclickListener eg
public class A implements OnClickListener
step2 Add onclicklistener to all buttons
button1 = (Button) findViewById(R.id.btn1);
button2 = (Button) findViewById(R.id.btn2);
button3 = (Button) findViewById(R.id.btn3);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
step3 write implementation of onClickMethod
#Override
public void onClick(View view) {
if (view == button1) {
//do button1 click action
} else if (view ==button2) {
//do button2 click action
} else if (view == button3) {
//do button3 click action
}