"Catch" Multiple Buttons with One Method - java

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();

Related

I Would Like To Have A Single Button Display A Different Line Of Text Each Consecutive Time It's Pressed in Android Studio

I'm extremely new to coding, so apologies if this question is trivial or the answer is easily found somewhere. I have searched, but I cannot find anything that helps.
Basically, I'm trying to code a simple, 2 button app in Android Studio.
Button1 is meant to simply display a series of commands to the user via text box.
Button2 merely resets.
My problem is, I would like Button1 to change what's displayed in the text view each time it is pressed, but I cannot figure out how to do so. I don't want to make 6 or 7 buttons.
Basically I would like it to run as follows;
Text = "Pick a number"
user presses Button1
Text = "Add 15" (This is as far as I've gotten)
user presses Button1
Text = "Multiply times 5"
user presses Button1 etc. etc. etc.
If anybody could please explain or usher me in the right direction, I would be greatly appreciative.
You can use button.setOnClickListener
public class MyActivity extends Activity {
EditText et;
Button button;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_layout_id);
et = (EditText)findViewById(R.id.edittext);
button = (Button)findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Perform your Logic here.
et.setText("New text");
}
});
}
}
you can use a globle and a swithchcase
public class MyActivity extends Activity {
EditText et;
int CLICKS=0;
Button button;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_layout_id);
et = (EditText)findViewById(R.id.edittext);
button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CLICKS++;
switch(clicks)
{
case 1:
et.setText("Pick a number");
break;
case 2:
et.setText("Add 15");
break;
case 3:
et.setText("Multiply times 5");
break;
}
}
});
}
}

Android Identifying Multiple Button

I have morethan 100 button in my MainLayout.xml and i want to handle click on each. I want to group all the button and then listen to click of the group button, get the ID and put it into String and then use it as my base id to query from my Sqlite Databse Table. How can i do this? so far i have this on my MainClass.java.
MainClass.java
public class MainClass extends AppCompatActivity implements View.OnClickListener {
Button B0,B1,B2,B3....;
String baseId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
buttonInitializer();
}
public void buttonInitializer(){
B0 = (Button)findViewById(R.id.B0); B0.setOnClickListener(this);
B1 = (Button)findViewById(R.id.B1); B1.setOnClickListener(this);
...
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.B0:
baseId = "B0";
break;
case R.id.B1:
baseId = "B1";
break;
..........
default:
break;
}
QueryFire(); // Fire a query
}
Public void QueryFire(){
//Fire the query with id of the clicked button
}
}
As you can see if i continue doing this, i will have Long Code, i want to shorten my code, instead of the above code, i'd like to group the button and then listen of each click just like RadioButton, but NOTE. i dont want to use RadioButton. I'm trying to implement this seudo code.
// Put the button into RelativeLayout or something and use it to group the button
// OnClick of Each Button inside the GroupButton:
// Get the ID of the Clicked Button:
// Put the ID of Button into String:
// and FIRE my query with ID of Button
Any help woul be appreciated! Thank You Very Much!!!
You should be able to specify a String for the "android:tag" attribute for each button in your xml layout, as well as an "android:onclick" attribute. This should eliminate the need for all of the findViewById() and setOnClickListener() calls.
Then, in your onClick method, you can just do something like baseId = (String) view.getTag()
Might be a bit of a stretch but why not use a ListView with a custom adapter? each adapter will hold a button (or whatever you want) and with every click on button you will get the id (the position of clicked element). Its far more easy on the memory as well :)

It Is fine to define all Widget ID with same Variable?

I mean is like this
button = (Button)findViewById(R.id.button1);
button = (Button)findViewById(R.id.button2);
button = (Button)findViewById(R.id.button3);
button = (Button)findViewById(R.id.button4);
button = (Button)findViewById(R.id.button5);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
//Do same logic
}
});
}
it is possible to define like that? or it can causes force close?
and one question again, it is okay to use copying ID from current xml to another xml? i mean the xml was different but the Widget and ID is same, and define the ID in diferrent class. Because it is more simple to copying than make the Same widget with new Id, it is okay?
example :
so in activityone.xml
i had this
so i was copy the widget to activitytwo.xml so they have a same Widget and ID
it is okay if i do like that?
That will only set the listener for button5. Every time you assign button you lose the previous assignment, so when you set the listener the variable button doesn't know that it used to be pointing to button1 to 4.
So no, it will not work.
I put a comment about your second question.
For that you should have single listener but five different buttons (Objects). Currently you are assigning every button one by one to same button reference. In that way your button will have R.id.button5 and in further code you won't have reference to your previous buttons butons1-4. So, while you add listener to the button you are actually adding listener to only button 5 and any other buttons will not have that listener.
First of all you need five different buttons and you should create class which implement the listener and add instance of that listener to your setOnClicklistener method or in a better way you can just specify android:onClick="onClick" in your xml and add onClick method in your activity.
FOR EXAMPLE :
//.. on create
Button button1 = (Button)findViewById(R.id.button1);
Button button2 = (Button)findViewById(R.id.button2);
Button button3 = (Button)findViewById(R.id.button3);
Button button4 = (Button)findViewById(R.id.button4);
Button button5 = (Button)findViewById(R.id.button5);
ListenerClass listener = new ListenerClass();
button1.setOnClickListener(listener);
button2.setOnClickListener(listener);
//..and so on
//Create class
public class ListenerClass implements View.OnClickListener {
//...
#Override
public void onClick(View view) {
//You can determine which button is clicked by view.getId()
//Add logic here
}
}
OR
public class YourActivity implements View.OnClickListener {
//...on create
button1.setOnClickListener(this);
button2.setOnClickListener(this);
//..and so on
//...
#Override
public void onClick(View view) {
//You can determine which button is clicked by view.getId()
//Add logic here
}
}
it is okay to use copying ID from current xml to another xml?
Yes it is fine but you should avoid using that as it may create confusion in a long run. In a wide project working with a team can create problem in understanding that. Other than that you can have same id because when you call findViewById it will refer to the current view and does not get influenced by ids of other views.

Do I need to add many methods, or is it possible to call one method

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;
}

Registering listener in java/android, a little question

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
}

Categories

Resources