Handling Multiple Buttons [duplicate] - java

This question already has answers here:
One OnClickHandler for multiple Buttons
(6 answers)
Closed 7 years ago.
I have an activity that is a full screen of 25 buttons. I was wondering if there was a more efficent was to create listeners for them so that they change colour when clicked instead of:
Button buttonA1;
Button buttonA2;
Button buttonA3;
...
buttonA1 = (Button) findViewById(R.id.buttonA1);
buttonA2 = (Button) findViewById(R.id.buttonA2);
buttonA3 = (Button) findViewById(R.id.buttonA3);
...
and then adding a listener for each...
Is it possible to condense all this into considerably less lines of code?

In xml file, you can implement OnClickListener for button like this :
...
<Button android:id="#+id/mybutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="myMethod" />
Then, in your java file
public void myMethod(View v) {
// does something very interesting
}

You can set in your XML file the android:onClick for each button.
android:onClick="onClick"
Then in your MainActivity you can use something like.
public void onClick(View v) {
//Handle the buttons
public void onClick(View v) {
switch(v.getId())
{
case R.id.button_a_id:
// handle button A click;
break;
case R.id.button_b_id:
// handle button B click;
break;
default:
throw new RuntimeException("Unknow button ID");
}
}
Hope it helps.

Related

Significance of using ID in switch statements in onClick()

I wanted to ask what was the significance of creating a switch statement when implementing the onClickListener interface for multiple buttons. Like, we're already calling the setOnClickListener for that particular button by saying button_name.setOnClickListener()
So what's the point of specifying the id's again in the switch statement ? Why is it necessary to do so ? doesn't the point of doing button_name.setOnClickListener() mean - "do what's in here for this button" ?
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Capture our button from layout
Button button = (Button)findViewById(R.id.corky);
Button button2 = (Button)findViewById(R.id.corky2);
Button button3 = (Button)findViewById(R.id.corky3);
// Register the onClick listener with the implementation above
button.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// do something when the button is clicked
// Yes we will handle click here but which button clicked??? We don't know
// So we will make
switch (v.getId() /*to get clicked view id**/) {
case R.id.corky:
// do something when the corky is clicked
break;
case R.id.corky2:
// do something when the corky2 is clicked
break;
case R.id.corky3:
// do something when the corky3 is clicked
break;
default:
break;
}
}
}
What I'm trying to ask is, doing button2.setOnCLickListener() means - "Do what's set by this function for button2" right ? if not then what is the actual purpose/function performed by setOnClickListener() ?
Since you have set clickListeners to 3 different buttons, the method
....onClick(View v){.....
is going to get called when you click any of those 3 buttons. If you click the button1 you do not want to perform task actually assigned for button3. So to check and find out which button was pressed the switch statement is necessary.
Alternatively you could have done this:
corkyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
// do something when the corky is clicked
}
});
playButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
// do something when the play is clicked
}
});
so on and so forth...
This way you don't need a switch statement as in this case you know which button is being clicked on, AS you're setting the clickListener AND ALSO specifiying what you wanna do there itself.
It's more of a clean look, a more readable code style structure. If you have multiple widgets who need click listener, by implementing View.OnClickListener interface
and overriding onClick gives a cleaner look.
and inside onClick(View view){
- you can also use if statement but when the number of widgets is more
then it becomes messy, that's why we use switch statement to look cleaner.
}
and
btn.setOnClickListener(this)
// telling the button to pass the interface
so that overridden onClick can listen to this.
But If you don't want that or you have only one widget for click
then just use this, no need to implement and override.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});

One OnClick handler for multiple buttons in a fragment

I have 3 buttons in a fragment that I want to use the same click event. How can this be achieved within a fragment?
XML
<Button
android:id="#+id/btn_1"
android:onClick="btnClick_DoSomething"
android:text="#string/one"/>
<Button
android:id="#+id/btn_2"
android:onClick="btnClick_DoSomething"
android:text="#string/two"/>
<Button
android:id="#+id/btn_3"
android:onClick="btnClick_DoSomething"
android:text="#string/three"/>
Java
#Override
public void btnClick_DoSomething(View v) {
}
Error
#Override (within the fragment Java class) becomes underlined in red and the following error is returned
Annontations are not allowed here
I want the onClick event to be the same for all 3 buttons
You dont need to write #Override annotation as you are not overriding the method. Just use
public void btnClick_DoSomething(View v) {
}
You will get a callback in this method at runtime.
you simply don't do it in XML, do it in Java instead:
<Button
android:id="#+id/btn_1"
android:text="#string/one"/>
<Button
android:id="#+id/btn_2"
android:text="#string/two"/>
<Button
android:id="#+id/btn_3"
android:text="#string/three"/>
then...
private final OnClickListener onClick = new OnClickListener(){
#Override
public void onClick(View view){
switch(view.getId()){
... cases...
}
}
somewhere initialising the views you do:
fragmentView.findViewById(R.id.btn_1).setOnClickListener(onClick);
fragmentView.findViewById(R.id.btn_2).setOnClickListener(onClick);
fragmentView.findViewById(R.id.btn_3).setOnClickListener(onClick);
}
What method are you trying to override? Do any of the parent classes have a method btnClick_DoSomething? You do not need to override anything when setting a click listener from a Layout XML. Just ensure that a method of the same name with a void return type and a View as its only argument exists in the activity class that will use this layout
The general way to distinguish clicks from different Views in the same onClick handler is to identify them by id
public void btnClick_DoSomething(View v){
switch(v.getId()){
case R.id.btn_1:
// handle click from button 1
break;
case R.id.btn_2:
// handle click from button 2
break;
case R.id.btn_3:
// handle click from button 3
break;
}
}
There are some misunderstandings here. To override a Click event, your Fragment need to implement the View.OnClickListener interface like this:
public class YourFragment extends Fragment implements View.OnClickListener{
#Override
public void onClick(View v) {
}
}
Note that the name of the method must be onCLick, must return void and recives a View as a parameter to be overrided from the interface. In this case you need to set a Listener to each button in your fragment:
btn1 = (Button) view.findViewById(R.id.btn_1);
btn1.setOnClickListener(this);
Inside this method you can control which object was clicked by it´s ID
#Override
public void onClick(View v) {
int id = v.getId();
switch(v.getId()){
case R.id.btn_1:
// handle click from button 1
break;
case R.id.btn_2:
// handle click from button 2
break;
case R.id.btn_3:
// handle click from button 3
break;
}
}
Or, you don't need to override the method, so remove the anotation that will work's fine :
public void btnClick_DoSomething(View v) {
switch(v.getId()){
case R.id.btn_1:
// handle click from button 1
break;
case R.id.btn_2:
// handle click from button 2
break;
case R.id.btn_3:
// handle click from button 3
break;
}
}
Instead of declaring the onClick method in the xml layout file, you could have your Fragment implement View.onClickListener interface, override onClick(), and set all 3 buttons onClickListener like this btn.setOnClickListener(this). Put the behavior you want for all 3 buttons in onClick(). All 3 will have the same behavior (unless you check which button the event came from in onClick()).

Support to setup onclick method for my login button

I'm brand new to this whole android coding and im trying to setup a login page for my app. I created the login button and im trying to setup the onClick thing for it but its not working. Ill paste my java file below
package com.example.user_000.appname;
import android.widget.EditText;
import android.view.View;
public class onClick {
EditText username = (EditText)findViewById(R.id.username);
EditText password = (EditText)findViewById(R.id.password);
public void login(View view){
if(username.getText().toString().equals("admin") && password.getText().toString().equals("admin")){
//correcct password
} else {
//wrong password
}
}
}
I am not changing anything in your code just i am providing you a way to get it correctly as you are missing lot of things
Button's onClick() method can be set up basically in 3 ways
Very first from xml side when you declare a button
<Button
android:layout_height="wrap_content"
android:layout_height="wrap_content"
android:text="Login"
android:onClick="login"/>
And then just make a method in associated java class with the same name as given in XML file like this
public void login(View v)
{
//do whatever you want here
}
Second way you can make an inner implementation anywhere in your class by simply making onClickListner() on Button,but you have to make sure to get button on java side by findViewById() method once you got it then you can set like this
Button b = (Button)findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do stuff here
}
});
third way is also simple you can implement OnClickListner in your whole class and then you can use it for multiple views clicks but i would say if you have a button only then no need to use this you can use above two methods in this one you can do this
b.setOnClickListener(this);
It will show you an error that methods are not implemented and then you can just use Alt + Enter and onClick() method will be implemented
#Override
public void onClick(View v) {
if(v.getId()==R.id.yourId) {
//do stuff here
}
}
Some useful links are below
Best practice for defining button events in android
Difference between OnClick() event and OnClickListener?
Button Click Listeners in Android

edittext validation [duplicate]

This question already has answers here:
Android EditText.setError() yields invisible error text
(5 answers)
Closed 9 years ago.
I have following small block of code to set validation on edit text when a button is pressed and display the validation message in a dialog.
Java Code
setContentView(R.layout.addnewcontacts);
Button buttonSave = (Button) findViewById(R.id.buttonSave);
final EditText editTextName = (EditText) findViewById(R.id.editTextName);
buttonSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (editTextName.getText().toString().length() == 0) {
editTextName.setError( "First name is required!" );
}
}
});
}
Code is working fine but the popup is not displaying text in it.
Screen shot :
Why popup is not showing text?
Call EditText.setError() with a SpannableStringBuilder object.
Check this previous SO question: Android EditText.setError() yields invisible error text
Use EditText.setTextColor(int color) to set the required color for the text element.
Just add edittext color into your xml file.
<EditText
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textColor="#android:color/black" />
it's very simple just follow the below code it is working fine.
final EditText et=(EditText)findViewById(R.id.editText1);
Button bt=(Button)findViewById(R.id.button1);
bt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(et.getText().toString().length()==0){
et.setError("it is wrong");
}
}
});
please check the theme you have applied .Use basic theme to check error text

Android one OnClick method for multiple buttons?

I started program little bit in android,
I have 3 buttons in a single activity.
I saw some example codes that assign the same OnClick event to all the buttons (even if they perform completely different action) and in the method Switch(id) case case case...
What is the better approach? one onClick method and switching or a lot of methods, one for each button?
Thanks.
Use this way:
#Override
public void onCreate(Bundle savedInstanceState) {
button1.setOnClickListener(onClickListener);
button2.setOnClickListener(onClickListener);
button3.setOnClickListener(onClickListener);
}
private OnClickListener onClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.button1:
//DO something
break;
case R.id.button2:
//DO something
break;
case R.id.button3:
//DO something
break;
}
}
};
If you want to reduce the coding lines then use View's OnClick() with switch statement and if you want to handle separately all click (for easily understanding and maintaining code) then use separate all button's onClick().
Update:
If you have declared Buttons in your Activity layout xml file, than write attribute android:onClick="" with same method name for all buttons and implement that method in your activity. Now you have one method for all buttons and in that method differentiate buttons with id.
Example:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button android:id="#+id/button1"
android:layout_width="wrap_content"
android:onClick="buttonOnClick"
android:layout_height="wrap_content"
android:text="Hello, I am a Button 1" />
<Button android:id="#+id/button2"
android:layout_width="wrap_content"
android:onClick="buttonOnClick"
android:layout_height="wrap_content"
android:text="Hello, I am a Button 2" />
<Button android:id="#+id/button3"
android:layout_width="wrap_content"
android:onClick="buttonOnClick"
android:layout_height="wrap_content"
android:text="Hello, I am a Button 3" />
</LinearLayout>
Now in your Activity implement buttonOnClick like,
public void buttonOnClick(View view)
{
switch(view.getId())
{
case R.id.button1:
// Code for button 1 click
break;
case R.id.button2:
// Code for button 2 click
break;
case R.id.button3:
// Code for button 3 click
break;
}
}
Or you can apply same switch case for dynamically added buttons in your activity,
like instead of buttonOnClick you have to use implemented View's OnClickListerner's onClick.
this.btnAddFriedtoFacebook = (Button) this.findViewById(R.id.btnAddFriedtoFacebook);
this.btnAddFriedtoFacebook.setOnClickListener(this.backButtonClickListener);
public OnClickListener backButtonClickListener = new OnClickListener()
{
public void onClick(final View view)
{
if (view == MatchInfoActivity.this.btnBack)
{
MatchInfoActivity.this.finish();
}
if( view == MatchInfoActivity.this.btnAddFried){
Intent i = new Intent(Intent.ACTION_VIEW);
MatchInfoActivity.this.startActivity(i);
}
if( view == MatchInfoActivity.this.btnAddBuddy){
Intent i = new Intent(Intent.ACTION_VIEW);
MatchInfoActivity.this.startActivity(i);
}
}
};
Here is the good way.
I think registering onClick in xml (layout) is better approach.
EDIT:
Found related threads :
Best practice for defining button events in android
best practices for handling UI events
Registered onClick event in the XML layout and then handle it in the code. This is how I would do it:
<Button
android:id="#+id/btplus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me"
android:onClick="onBtnClicked">
Method in .class
public void onBtnClicked(View v) {
switch (v.getId()) {
case R.id.btplus:
Toast.makeText(getApplicationContext(), "Plus is clicked" + "+", Toast.LENGTH_SHORT).show();
break;
case R.id.btminu:
Toast.makeText(getApplicationContext(),"Minus is clicked" + "-", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
Little addition to #Nguyen answer.
findViewById(R.id.buttonOne).setOnClickListener(buttonClickListener);
.... .... .... ....
findViewById(R.id.buttonN).setOnClickListener(buttonClickListener);
private View.OnClickListener buttonClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonOne:
// do something
break;
.... .... .... ....
case R.id.buttonN:
// do something
break;
}
}
};
This could be useful, if you don't want to initialize the button variable, but want to track button click event. Thanks!

Categories