[Guide] Listeners in Java development

Search This thread

mohamedrashad

Senior Member
Nov 15, 2012
1,087
618
26
ismailia

You are new to java development and want to get buttons working?
Maybe you are a Pro but want a reminder?
whatever you are this Guide is to help you to make buttons/check boxes...etc working and functional


Some people are distracted between guides over internet and want the easiest way to get their project working, me too :p



Steps :

1-Define the button :

Code:
Button btn1;
Checkbox chkbox1;
RadioButton radio1;

2- Intialize it :

Code:
btn1 = (Button) findViewById(R.id.btn1);
chkbox1= (Checkbox ) findViewById(R.id.chkbox1);
radio1= (RadioButton) findViewById(R.id.radio1);

3-Add the listener :

Button:

Code:
btn1.setOnClickListener(new OnClickListener() {

			@SuppressWarnings("deprecation")
			@Override
			public void onClick(View arg0) {

                  //Write awesome code here
			}
		});

CheckBox :

Code:
chkbox1.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {

				if (start.isChecked()) {

				//if the checkbox checked
					
				} else {
				
					//if not checked 
				}
			}
		});
	}

radio button:

Code:
public void onRadioButtonClicked(View view) {
  
    boolean checked = ((RadioButton) view).isChecked();
    
 
    switch(view.getId()) {

        case R.id.radio1:
            if (checked){

                     }
         else{

      }
           
            break;
       
    }
}

or use it in a radio Group :

Code:
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.radio1:
            if (checked)
            //Write code
            break;
        case R.id.radio2:
            if (checked)
               //Write code
            break;
    }
}


Also insted of this you can use a onCheckedChanged for a radio button (Thanks for GalaxyInABox)

Code:
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
        switch (radioGroup.getCheckedRadioButtonId()) {
            //Code
        }
}


____________________________________________________________________
____________________________________________________________________


Also you can implement a Onclicklistener for the whole class to save resources : (thanks for @Jonny )

after defining and initializing your objects add this :


Code:
OnClickListener click_listener = new OnClickListener() {
			public void onClick(View view) {
				int id = view.getId();
				if (id == your_id) {
					//do stuff for this object
				} else if (id == your_id2) {
		        	//do other stuff for diffrent object
				} else if (id == your_id3) {
		        	//and so on
				}
			}
		};


To do list :

-add on touch listeners
-add on drag listeners





Note : you can add a click listener to almost any thing (Textview or imageView or even EditText) just using the same method of adding listener to button

also there is some other ways to add a listener but this is the fastest and less disturbing :good:

If this guide is useful, press thanks :D
 
Last edited:

giuliomvr

Senior Member
May 16, 2013
189
235
Cologne
@ OP
CheckBox and RadioButtons don't they provide a CheckedChangeListener ?

Yes, and now you can use
Code:
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
        switch (radioGroup.getCheckedRadioButtonId()) {
            //Code
        }
}
to get the checked button. They are pretty much the same, but you can use view.getTag() easier in the first one.

And @mohamedrashad please show how to put the listener into a inner class. Many people don't know/use it, but it's that useful!
 
  • Like
Reactions: mohamedrashad

sak-venom1997

Senior Member
Feb 4, 2013
928
415
Lucknow
Yes, and now you can use
Code:
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
        switch (radioGroup.getCheckedRadioButtonId()) {
            //Code
        }
}
to get the checked button. They are pretty much the same, but you can use view.getTag() easier in the first one.
I meant that the op shuld edit this guide and use those instead of OnCickListeners :cool:
And @mohamedrashad please show how to put the listener into a inner class. Many people don't know/use it, but it's that useful!

ya new with java8 it will be a nice usage scenario of lambadas :D

Sent from my GT-S5302 using Tapatalk 2
 
Last edited:

mohamedrashad

Senior Member
Nov 15, 2012
1,087
618
26
ismailia
Yes, and now you can use
Code:
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
        switch (radioGroup.getCheckedRadioButtonId()) {
            //Code
        }
}
to get the checked button. They are pretty much the same, but you can use view.getTag() easier in the first one.

And @mohamedrashad please show how to put the listener into a inner class. Many people don't know/use it, but it's that useful!

@ OP
CheckBox and RadioButtons don't they provide a CheckedChangeListener ?

Sent from my GT-S5302 using Tapatalk 2

ok, i will add this
 

SKAm69

Senior Member
Oct 2, 2009
659
121
Also, an activity can be a listener. In this case:
MyActivity implements onClickListener {

btn1.setOnClickListener(this);

public void onClick (View v) {
//your code
}
}
 
  • Like
Reactions: mohamedrashad

mohamedrashad

Senior Member
Nov 15, 2012
1,087
618
26
ismailia
  • Like
Reactions: mohmmed985

Jonny

Retired Forum Moderator
Jul 22, 2011
9,293
9,616
If you have multiple clickable objects then it's best to use just 1 onClickListener for all of them and use a switch on their ID's. This reduces resource usage as you only have 1 listener, not 5, 10 or however many you would have otherwise. It's not essential for this but it is a best practice if you want to streamline your code.

Mobile right now so I can't chuck up an example until tomorrow evening or so.
 
  • Like
Reactions: mohamedrashad

giuliomvr

Senior Member
May 16, 2013
189
235
Cologne
As @Jonny already pointed out: Use your class as a listener instead of creating a new (anonymous) inner class! Say you have a ListView, instead of doing this:
Code:
class MyFragment extends Fragment {
    private void someMethod() {
        ((ListView) getView().findViewById(R.id.someListView)).setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //Code...
            }
        });
    }
}
you can do this:
Code:
class MyFragment extends ListFragment implements AdapterView.OnItemClickListener, View.OnClickListener {
    private void someMethod() {
        ((ListView) getView().findViewById(R.id.someListView)).setOnItemClickListener(this);
    }
    
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //Code...
    }
}
This may look stupid, but when you have many listeners, you can un-clutter it. In my opinion this is the best way. You can also add "this" class as listener for as many ui elements as you want(because all of them extend view, you can use one OnClickListener), then you only need to have a switch statement to distinguish between the views. And voila, you prevented cluttering the code with boilerplate stuff.
 

Jonny

Retired Forum Moderator
Jul 22, 2011
9,293
9,616
Example using code in an app I'm making - app for my school.

Code:
@Override
	    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
			
                        // Some code here for view/layouts etc

			websitebutton = (Button) view.findViewById(R.id.website_btn);
			facebookbutton = (Button) view.findViewById(R.id.facebook_btn);
			twitterbutton = (Button) view.findViewById(R.id.twitter_btn);
			websitebutton.setOnClickListener(handler);
			facebookbutton.setOnClickListener(handler);
			twitterbutton.setOnClickListener(handler);

			return view;
		}

		OnClickListener handler = new OnClickListener() {
			public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.website_btn :
                        Uri website = Uri.parse("http://wirralgrammarboys.com/");
                        Intent websiteintent = new Intent(Intent.ACTION_VIEW, website);
                        startActivity(websiteintent);
                        break;
                    case R.id.facebook_btn :
                        Uri facebook = Uri.parse("https://www.facebook.com/WirralGSB");
                        Intent facebookintent = new Intent(Intent.ACTION_VIEW, facebook);
                        startActivity(facebookintent);
                        break;
                    case R.id.twitter_btn :
                        Uri twitter = Uri.parse("https://twitter.com/WGSB");
                        Intent twitterintent = new Intent(Intent.ACTION_VIEW, twitter);
                        startActivity(twitterintent);
                        break;
				}
			}
		};
 
Last edited:
  • Like
Reactions: mohamedrashad

mohamedrashad

Senior Member
Nov 15, 2012
1,087
618
26
ismailia
Example using code in an app I'm making.

Code:
@Override
	    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
			
                        // Some code here for view/layouts etc

			websitebutton = (Button) view.findViewById(R.id.website_btn);
			facebookbutton = (Button) view.findViewById(R.id.facebook_btn);
			twitterbutton = (Button) view.findViewById(R.id.twitter_btn);
			websitebutton.setOnClickListener(handler);
			facebookbutton.setOnClickListener(handler);
			twitterbutton.setOnClickListener(handler);

			return view;
		}

		OnClickListener handler = new OnClickListener() {
			public void onClick(View view) {
				int id = view.getId();
				if (id == R.id.website_btn) {
					Uri website = Uri.parse("http://wirralgrammarboys.com/");
			        Intent websiteintent = new Intent(Intent.ACTION_VIEW, website);
			        startActivity(websiteintent);
				} else if (id == R.id.facebook_btn) {
		        	Uri facebook = Uri.parse("https://www.facebook.com/WirralGSB");
		        	Intent facebookintent = new Intent(Intent.ACTION_VIEW, facebook);
			        startActivity(facebookintent);
				} else if (id == R.id.twitter_btn) {
		        	Uri twitter = Uri.parse("https://twitter.com/WGSB");
		        	Intent twitterintent = new Intent(Intent.ACTION_VIEW, twitter);
		        	startActivity(twitterintent);
				}
			}
		};

i'm adding this to OP if you don't mind jonny :cool:
 

Rebound.co

Member
Jul 19, 2014
12
0
Hey what about starting a new activity with onClickListiner

Sent from my M3S_D7 using XDA Free mobile app

---------- Post added at 03:57 PM ---------- Previous post was at 03:49 PM ----------

Hey and do u mind sending a source codes.zip file

Sent from my M3S_D7 using XDA Free mobile app
 

Jonny

Retired Forum Moderator
Jul 22, 2011
9,293
9,616
Hey what about starting a new activity with onClickListiner

Sent from my M3S_D7 using XDA Free mobile app

---------- Post added at 03:57 PM ---------- Previous post was at 03:49 PM ----------

Hey and do u mind sending a source codes.zip file

Sent from my M3S_D7 using XDA Free mobile app

in the onClick method just have this code:


Code:
startActivity(new Intent(this, YourActivity.class));
 

Top Liked Posts

  • There are no posts matching your filters.
  • 21

    You are new to java development and want to get buttons working?
    Maybe you are a Pro but want a reminder?
    whatever you are this Guide is to help you to make buttons/check boxes...etc working and functional


    Some people are distracted between guides over internet and want the easiest way to get their project working, me too :p



    Steps :

    1-Define the button :

    Code:
    Button btn1;
    Checkbox chkbox1;
    RadioButton radio1;

    2- Intialize it :

    Code:
    btn1 = (Button) findViewById(R.id.btn1);
    chkbox1= (Checkbox ) findViewById(R.id.chkbox1);
    radio1= (RadioButton) findViewById(R.id.radio1);

    3-Add the listener :

    Button:

    Code:
    btn1.setOnClickListener(new OnClickListener() {
    
    			@SuppressWarnings("deprecation")
    			@Override
    			public void onClick(View arg0) {
    
                      //Write awesome code here
    			}
    		});

    CheckBox :

    Code:
    chkbox1.setOnClickListener(new OnClickListener() {
    			public void onClick(View v) {
    
    				if (start.isChecked()) {
    
    				//if the checkbox checked
    					
    				} else {
    				
    					//if not checked 
    				}
    			}
    		});
    	}

    radio button:

    Code:
    public void onRadioButtonClicked(View view) {
      
        boolean checked = ((RadioButton) view).isChecked();
        
     
        switch(view.getId()) {
    
            case R.id.radio1:
                if (checked){
    
                         }
             else{
    
          }
               
                break;
           
        }
    }

    or use it in a radio Group :

    Code:
    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.radio1:
                if (checked)
                //Write code
                break;
            case R.id.radio2:
                if (checked)
                   //Write code
                break;
        }
    }


    Also insted of this you can use a onCheckedChanged for a radio button (Thanks for GalaxyInABox)

    Code:
    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int i) {
            switch (radioGroup.getCheckedRadioButtonId()) {
                //Code
            }
    }


    ____________________________________________________________________
    ____________________________________________________________________


    Also you can implement a Onclicklistener for the whole class to save resources : (thanks for @Jonny )

    after defining and initializing your objects add this :


    Code:
    OnClickListener click_listener = new OnClickListener() {
    			public void onClick(View view) {
    				int id = view.getId();
    				if (id == your_id) {
    					//do stuff for this object
    				} else if (id == your_id2) {
    		        	//do other stuff for diffrent object
    				} else if (id == your_id3) {
    		        	//and so on
    				}
    			}
    		};


    To do list :

    -add on touch listeners
    -add on drag listeners





    Note : you can add a click listener to almost any thing (Textview or imageView or even EditText) just using the same method of adding listener to button

    also there is some other ways to add a listener but this is the fastest and less disturbing :good:

    If this guide is useful, press thanks :D
    2
    i'm adding this to OP if you don't mind jonny :cool:

    That's fine - if I didn't want people to use/adapt/learn from the code then I wouldn't put it up, use it as you want ;) :good:

    Sent from my HTC One using Tapatalk
    1
    @ OP
    CheckBox and RadioButtons don't they provide a CheckedChangeListener ?

    Sent from my GT-S5302 using Tapatalk 2
    1
    @ OP
    CheckBox and RadioButtons don't they provide a CheckedChangeListener ?

    Yes, and now you can use
    Code:
    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int i) {
            switch (radioGroup.getCheckedRadioButtonId()) {
                //Code
            }
    }
    to get the checked button. They are pretty much the same, but you can use view.getTag() easier in the first one.

    And @mohamedrashad please show how to put the listener into a inner class. Many people don't know/use it, but it's that useful!
    1
    You can also add onClick property in XML and then handle it in a code.