I found the code segment below in [this tutorial][1]. I don't understand what exactly happens. It seems like the button is created and that a listener is then set to listen for when it's clicked, but why is the entire onClick(View view) method inside the (...) of the sendMail.setOnClickListener()?
Regarding setOnClickListener, Eclipse said:
Register a callback to be invoked when this view is clicked. If this view is not clickable, it becomes clickable.
So am I correct in saying that the structure is as it is to almost simultaneously see if the button is clickable, make it clickable if it isn't and create a listener for the button?
But I still don't understand why it was written and structured like this:
Button sendMail = (Button) findViewById(R.id.send_email);
sendMail.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Mail m = new Mail("email#gmail.com", "password");
m.setTo("email#gmail.com");
m.setFrom("email#gmail.com");
m.setSubject("This is an email sent using my Mail JavaMail wrapper from an Android device.");
m.setBody("Email body.");
try {
m.addAttachment("/sdcard/filelocation");
if(m.send()) {
Toast.makeText(m, "Email was sent successfully.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Email was not sent.", Toast.LENGTH_LONG).show();
}
} catch(Exception e) {
Toast.makeText(getApplicationContext(), "There was a problem sending the email.", Toast.LENGTH_LONG).show();
Log.e("MailApp", "Could not send email", e);
}
}
});
In my mind it should be:
sendMail.setOnClickListener();
sendMail.onClick(this);
public void onClick(View view) {...}
Any comments or Register a callback to be invoked when this view is clicked. If this view is not clickable, it becomes clickable.
This is basically a subclass. This method is known as anonymous subclassing. It allows to you to create a subclass and use it together.
Anonymous subclass do not have constructors as the class has no name. For that you need to use instance initialisers. Basically these classes are used when creating another class file for it feels redundant and if you want to keep the class code together in the same block(Atleast that why i use it for).
It is called an anonymous class. Instead of creating a new class with the class keyword, you just use the syntax new <superclass-or-interface-name>() { ... } with all the required methods.
Read more about anonymous classes at Wikibooks
It's called an anonymous inner class, its a common Java pattern. You are free to define an explicit class that implements the method and set your listener to it, instead.
That's just how it works when you create a new instance of the Listener inside the setOnClickListener() method. Nothing weird about that at all.
Alternatively, you can set a method for android:onClick in the button XML side. In code, you'll need to do the following:
public void testMethod(View v) {
// code
}
Related
I am trying to call ViewModel from my activity in a snackbar and since it requires a onClickListener it doesn't let me just do a simple
Snackbar.make(mViewBinding.root, "Note has been deleted", Snackbar.LENGTH_LONG).apply {
setAction("Undo", mViewModel.insertNote(event.data!!))
}
So the solution is to call with a View.OnClickListener but I found a weird solution that I'm trying to understand and I'd like to know if any of you could explain to me this.
Snackbar.make(mViewBinding.root, "Note has been deleted", Snackbar.LENGTH_LONG).apply {
setAction("Undo"){
mViewModel.insertNote(event.data!!)
}
}
Question: Why does setting a "{" works the same way? Is it an anonymous function?
i am new and learning , i have checked many related posts but still my few following questions are unanswered...[Edited ]the language is java...
following is the way to handle the click on button but can any one explain
1, why i have to declare the anonymous class ,
2, how i know that i have to declare the anonymous class here or any where else could ?
3, why i cannot use simple the btn.setOnClickListener(); why i must have to call anonymous class here ... below line is simple to do the task ...!!
btn.setOnClickListener();
why to make two more lines of code ...? i.e
#override public void onClick (View v) {....}
======================
Button btnCount = (Button) findViewById(R.id.btnCountId);
btnCount.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) { ...... }
});
You are using a Java entity called an "interface".
View.setOnClickListener accepts an object of type "OnClickListener". So you first need to create an object of such a type.
The Object OnClickListener is indeed an interface with one function "onClick", so to create an object of that type you need to implement it (define all the functions in the interface) - in this case, only one.
OnClickListener myClickListener=new OnClickListener() {
#Override // override means you are implementing a function in the interface or a derived class
public void OnClick(View v) {
// the button has been pressed
}
};
and then you can assign it to a view:
myButton.setOnClickListener(myClickListener);
or to many views:
myButton1.setOnClickListener(myClickListener);
myButton2.setOnClickListener(myClickListener);
myButton3.setOnClickListener(myClickListener);
In Java you'll find objects use listener interfaces to communicate events.
Mind that more complex objects use interfaces that can have several methods instead of just one, that's when the simplification you see is not that handy.
Imagine an object "Girl" that has a method "flirt" that you can invoke to ask her for dinner. The Girl will take some time to decide, then communicate one of a lot possible answers with the same interface.
OnGirlFlirtListener myGirlFlirtListener=new OnGirlFlirtListener() {
#Override
public void onGirlSaidYes() {
// invite the girl to have dinner
}
#Override
public void onGirlSaidNo() {
// find another girl or hang with your mates instead
}
#Override
public void onGirlSaidMaybe() {
// ask her later
}
#Override
public void onParentsHateMe() {
// forget about that girl
}
}
Then you can do:
mGirl.flirt (myGirlFlirtListener);
And the code is indeed elegant: With one interface you control all the possible answers! It's the same for a lot of objects in java (and Android).
Instead of creating the listener as an object, and setting it, you can as well create it as an anonymous class if you won't reuse it, of course.
EDIT
How to create a generic clicklistener?
Sometimes, in the same dialog, you have 15 or 20 buttons that do more or less the same, and only differ in a detail. Although you can perfectly crete 20 clicklisteners, there's a cooler way taking advantage of View.setTag() function.
setTag allows you to store whatever object you want to any view. You use that do distinguish, inside a clicklistener, which button was pressed.
So imagine you have 5 buttons: Brian, Peter, Loise, Krasty and Sue:
mButtonPeter.setTag("Peter Griffin");
mButtonLouise.setTag("Louise Griffin");
mButtonBrian.setTag("Brian");
mButtonKrasty.setTag("Krasty");
mButtonSue.setTag("Sue");
OnClickListener personClickListener=new OnClickListener() {
#Override
public void OnClick(View buttonPressed) {
String person=(String)(buttonPressed.getTag());
// you pressed button "person"
Toast.makeText(buttonPressed.getContext(), "Hey, "+person+", how is it going!!", Toast.LENGTH_SHORT).show();
}
};
mButtonPeter.setOnClickListener(personClickListener);
mButtonLouise.setOnClickListener(personClickListener);
mButtonBrian.setOnClickListener(personClickListener);
mButtonKrasty.setOnClickListener(personClickListener);
mButtonSue.setOnClickListener(personClickListener);
Isn't it cool?
When you are "setting an onClickListener" what you are doing is telling: "when this button is clicked, execute this code".
The code to be executed is implemented in the provided annonymous function.
You can't simply do btn.setOnClickListener() without an argument because that would not provide the information regarding which behaviour to perform when the button is clicked.
I'm a total beginner in coding for Android and java in general and so far in various tutorials I found two ways of handling buttons being clicked.
The first one:
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//do your thing
}
});
The second one involves putting android:onClick="someMethod" in a button's properties in the main.xml and then simply creating the method someMethod in the activity.
I was wondering what is the difference in those two approaches. Is one better than another? Or do they work only subtly differently? To me they seem to do the same :P
Thank!
I was wondering what is the difference in those two approaches. Is one
better than another?
The result is same. But difference is in readability of code.
android:onClick="someMethod"
this approach i don't recommend to you.
I recommend to you use anonymous classes like you meant above.
Also your class can implement for example View.OnClickListener and then you only have to implement onClick() method and you can have one method for many widgets.
public class Main extends Activity implements View.OnClickListener {
public void onClick(View view) {
switch(view.getId()) {
case R.id.startBtn:
// do some work
break;
case R.id.anotherWidgetId:
// do some work
break;
}
}
}
I think this is also good practice, you have only one method and code have less lines and is cleaner.
In first one: You are defining a method pragmatically, that will be called at every press of the button.
In Second one: you are mentioning method name of the activity that will called when button will be pressed.
It totally depends upon your preference which way you like to set a click listener.
Personally, I like to set click listener pragmatically, so that I know which code will execute at onClick of a Button, while going through code.
When you use android:onClick="someMethod", the method is on the activity that holds the clicked view. If you're using this on a list item, it'll be more convenient (in some cases) to have the click handled on the activity.
If you'll use the anonymous class approach, you'll need to set it on the adapter, which not always have access to the activity (and if so - it could get messy..). So if you need stuff from the activity that's holding you list (holding that clickable item) - I think it'll be cleaner to use the android:onClick approach.
Besides that - it's pretty much the same. Be sure to document the methods you call with android:onClick, since it's sometimes hard to track their source later.
To handle double click on android button
// These variables as global
private final static long DOUBLE_CLICK_INTERVAL=250;
private static boolean doubleClick=false;
private static long lastClickTime=0;
private static Handler handler;
// In button method
long clickTime=SystemClock.uptimeMillis();
if(clickTime-lastClickTime <= DOUBLE_CLICK_INTERVAL) { // If double click...
Toast.makeText(getApplicationContext(), "Double Click Event",Toast.LENGTH_SHORT).show();
doubleClick=true;
} else { // If not double click....
doubleClick=false;
handler=new Handler();
handler.postDelayed(new Runnable(){
#Override
public void run(){
if(!doubleClick){
Toast.makeText(getApplicationContext(),"Single Click Event",Toast.LENGTH_SHORT).show();
}
}
}, DOUBLE_CLICK_INTERVAL);
}
lastClickTime=clickTime;
I'm trying to call a function present in one class from another class by creating its object. Somehow it's not working. The new activity doesn't load.
My java code:
public class MessagesActivity extends TabActivity {
public WorkEntryScreenActivity workEntryObject = new WorkEntryScreenActivity() ;
public void AddWorkEntryClick(View v) {
workEntryObject.newWorkEntry();
}
}
The other class:
public class WorkEntryScreenActivity extends Activity {
public void newWorkEntry() {
try {
Intent i = new Intent(this, WorkEntryActivity.class);
i.putExtra("CurDate", mDateDisplay.getText());
i.putExtra("DD", String.valueOf(mDay));
i.putExtra("MM", String.valueOf(mMonth));
i.putExtra("YYYY", String.valueOf(mYear));
startActivity(i);
finish();
} catch (Exception e) {
System.out.println("Exception" + e.getStackTrace());
Log.d(TAG, "Exception" + e.getStackTrace());
}
}
}
You must create your workEntryObject first (it's not C++). Like this
public WorkEntryScreenActivity workEntryObject=new WorkEntryScreenActivity();
Also, I highly recommed you to read Android Basics
http://developer.android.com/guide/index.html
#biovamp is correct. It looks like you have a null reference that you're trying to call a method on. In order to call a non-static method, you need a instance of that object.
From the naming of your method, it looks like you might be trying to re-use some of your UI in another part of your application. In Android, the way to accomplish that is through Intents and Activities. If you're not familiar with those or how to use them, I would highly suggest researching them.
I'm new to Java and Android. I have a piece of code that is used for multiple activities so I moved it into its own library .java file. However, now my findViewById return null where they used to return the right stuff when they were part of the main Activity file with onCreate() and setContentView() calls. How do I make it work inside my library?
Call from the Activity class:
helper.popupControl(getListView(), getBaseContext(), "on");
The code in the libruary:
public class Helper extends ListActivity {
public void popupControl (View v, Context context, String on_off) {
Animation aFilm = AnimationUtils.loadAnimation(context, R.anim.fade_in);
aFilm.reset();
View vFilm = (View) v.findViewById(R.id.gray_out_film);
if(vFilm==null) {
Toast maxToast = Toast.makeText(context, "View is null! "+R.id.gray_out_film+", View:"+v.toString(), Toast.LENGTH_LONG);
maxToast.setGravity(Gravity.CENTER, 0, 0);
maxToast.show();
} else {
Toast maxToast = Toast.makeText(context, "View is not null!", Toast.LENGTH_SHORT);
maxToast.setGravity(Gravity.CENTER, 0, 0);
maxToast.show();
}
}
}
This happened to me and the solution was to delete the main.xml from the new project. Somehow it was interfering with the main.xml from the library project even though I was referring to the fully qualified name (ex: library.package.R.layout.main).
Call Activity.setContentView(int resID) before calling findViewbyId()
What you're trying to do seems 'icky' but here's how it would be done.
You'll need to pass the View from the Activity...findViewbyId() is its Member function.
If you provide some sample code, i could be more helpfull.
Edit: Confused Context with View. Oops!