I'm using onBackPressed() method in my app in few places.
In every place I want this method to do other stuff.
When user is in X layout I want to Back button does somethink else than in Y layout, so I'm thinking that the best solution would be to use arguments in onBackPressed method.
For example in X onBackPressed(0); and in Y onBackPressed(1); etc.
#Override
public void onBackPressed(int c){
if(c==0)Toast.makeText(getApplicationContext(), "This is X", Toast.LENGTH_SHORT).show();
if (c==1)Toast.makeText(getApplicationContext(), "This is Y", Toast.LENGTH_SHORT).show();
}
But it does not work.
Do You have any ideas what can I do to make it work ? Or is there any better solution for this problem?
you are overriding a framework method and you can't pass it any other parameters than those defined by the API. However you can create an own method to check what you need like:
#Override
public void onBackPressed(){
switch(checkLayout()){
case 1: //do stuff
break;
case 2: .....
}
}
And to extend CommonsWare's comment a little: yes, users are not "in a certain layout". Users are interacting with a certain Activity that is hosting a certain layout. If you don't really understand what this means, you should probably consult this document: http://developer.android.com/reference/android/app/Activity.html
The way overriding methods in Android works is that you must exactly duplicate the method header. When you change it, it will still compile, but Java will read it as an overloaded method and thus not do anything with it because it is never called.
You would be a lot better off handling an instance variable outside of onBackPressed() and then handling it when it's actually pressed.
The following is a simple implementation.
//Your instance variable
boolean myRandomInstanceVariable = true;
#Override
public void onBackPressed()
{
if(myRandomInstanceVariable)
{
//do stuff
}
else
{
//do other stuff
}
}
Create a field in your class set it to some value in some place to some other value in some other place. Then in onBackPressed() check that field's value and proceed accordingly.
Related
Tapping the button multiple times opens many new screens(Activities). To prevent this I attached a flag to prevent this. But it may cause memory leaks. After searching a lot I found one solution. It is to attach the OnClick listeners onResume and set them null on onDetach and when the button is clicked. But I am finding it difficult to implement this.
My Code :-
private static int flag = 0;
#Override
public void onStart() {
super.onStart();
binding.createEventFab.setOnClickListener(view ->{
Intent intent = new Intent(getActivity(), CreateEventActivity.class);
if(flag == 0){
startActivity(intent);
flag++;
}
});
}
#Override
public void onResume() {
super.onResume();
flag = 0;
}
Thanks in advance!
I don't think so there is a leak here, but the real problem is that you are allowing user to press button multiple times, so you need debouncing listener.
The best what you can do is use RxBinding, since you can easy use it in another classes.
Here is sample code below:
RxView.clicks(/* Your view */)
.throttleFirst(2, TimeUnit.SECONDS)
.subscribe(s -> { /* Your code */ });
or in Kotlin, with nice extension
fun View.actionOnClick(function: () -> Unit): Disposable {
return clicks()
.throttleFirst(2, TimeUnit.SECONDS)
.subscribe { function() }
}
Don't forget to add these to CompositeDisposable and clear() them in onDestroy() (for Activity) or onDestroyView() (for Fragment) method.
Another option is use ButterKnife with #OnClick(/* viewId */), but RxBinding is preferred if you would like to easy switch to Kotlin in future (and for Kotlin, another possibility is use coroutines, but deboucers using coroutines can be hard to implement for some cases, like watcher for EditText).
You can set your click listeners in a normal way. And you can set the launchMode of the activity to singleTop in your Manifest.xml file. Your activities shouldn't leak. For further reading you can take a look here about the launchMode
I'm learning android development from Udacity course created by google, in an exercise, it is asked to create a score record for two teams playing basketball. the app looks like :
.
You can guess what each button does ....
To do that they create 6 methods (addThreePointToTeamA, addTwoPointToTeamA...) for each button. but I think that two methods (addTeamA, addTeamB) are enough if I could pass an int parameter correspond to the number of points to add to each method .
So I wonder if it is possible to do that ? and if not, why ?
Thank you in advance
EDIT
here is what I wish to do :
in the layout.xml :
<Button
...
android:text="+3 POINTS"
android:onClick="addThreeTeamA(3)"
/>
then in the MainActivity.java:
public void addThreeTeamA(int point){
....
}
It is technically possible to implement just only one Click Listener but not in the way you asked for since there is no a way to pass parameter to a click listener. Instead, you need to define android:id for every single button and use this approach.
public void buttonClicked(View v) {
switch (v.getId()) {
case R.id.btnAddTeamAThree:
// Add 3 points to Team A
break;
case R.id.btnAddTeamATwo:
// Add 2 points to Team A
break;
case R.id.btnAddTeamBThree:
// Add 3 points to Team B
break;
case R.id.btnAddTeamBTwo:
// Add 2 points to Team B
break;
...
}
}
The answer is simple you can definitely do that.
I would say, think about your design though.
Here is what I would Recommend:
// Setup an interface for common team behaviors
interface Team {
void addPoints(int points);
int getPoints();
}
// implement that interface per Team
class TeamA implements Team {
private int points;
public TeamA(){
this.points = 0;
}
#Override
public void addPoints(int points){
this.points += points;
}
#Override
public int getPoints(){
return this.points;
}
}
And do the same for TeamB!
then create a method in your Activity or whatever class your calling to add from:
public void addPoints(int points, Team team){
team.addPoints(points);
}
Good Luck and Happy Coding!
They created 6 methods for your better understanding. Once you get what they want to perform than you can enhance it. Yes you can enhance it by making generic methods for team-A and team-B. Its totally depend on your logic. Hope i answer your question.
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.
How can I call finish() and other non static methods from a DialogFragment in the activity that created it? I have tried passing messages from the OnClickLisener in the DialogFragment, to no avail.
I have a really simple app, conssting of a MainActivity and DialogFragment:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.activity);
showDialog();
}
public void showDialog() {
DialogFragment newFragment = new ConfirmDialog();
newFragment.show(getFragmentManager(), "dialog");
}
}
And the Dialog is again very simple:
public class ConfirmDialog extends DialogFragment {
#Override
public AlertDialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Confirm you want to continue?")
.setPositiveButton("Yes.", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//finish() MainActvity
}
})
.setNegativeButton("No.", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//Do nothing in MainActity
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
There are many options. One of them is define an interface with a single method inside.
Have the dialog caller implement that interface.
Keep a global variable pointing to the caller.
Set the variable in the onAttach(Activity activity) method.
Null that variable in the onDetach() method.
Call the variable (interface member) method in the onClick.
Example:
public class MainActivity extends Activity implements MyInterface {
// ...
#Override
public void onChoose() { finish(); }
}
And inside ConfirmDialog:
public static interface MyInterface {
public void onChoose();
}
private MyInterface mListener;
#Override
public void onAttach(Activity activity) {
mListener = (MyInterface) activity;
super.onAttach(activity);
}
#Override
public void onDetach() {
mListener = null;
super.onDetach();
}
And then call mListener.onChoose() anywhere inside your class.
I know this has been marked as accepted, but I figured I could provide more feedback to the discussion.
A note about using or not interfaces. Andy's answer works just as right as mine, hence why I said "There are many options. One of them is...".
However, the reason why I prefer interfaces for this particular problem is because most of the times you're going to extend and reuse simple/common confirmation dialogs like that. hey are too generic to be "wasted" (or worse: duplicated if different event actions arise).
Unless you are deadly sure that you are going to use that only once, for one purpose (finishing), you generally should avoid hardwiring (and simplifying) the implementation details of the Activity in your dialog class. Flexibility, abstraction and efficiency. Less code to maintain.
And yes, there is a telltale that you may need that: the public keyword that you're using, especially if it's in a self-contained class file, which begs for reuse (too). Otherwise, you should be hiding that class inside your main Activity, since the implementation details (would) relate only to that one. Also, you would be removing the public keyword.
Yes, you could use for more than one Activity, but you'd be limited to finish()ing. The interface will give you flexibility to do whatever you want in each Activity. In other words, it's up to the implementer to define how it should itself behave for that event. You self-contain implementation details.
As a sidenote, what I do is create a package with all dialogs I may need for my application. For confirmation dialogs like that, I reuse for different messages and buttons. I provide defaults, but also allow for change using setArguments. And I keep the interfaces related so I don't need to create one interface for each dialog. The implementer responds according to which dialog triggered the "dialogs callback". Flexibility, abstraction and efficiency, all while avoiding things humorously called Hydra and Royal Family. So. In the end, like I said, many options. Don't over-engineer, but don't simplify too much too early (leave room for graceful expansion).
It's more important to understand advantages and pitfalls than choosing this or the other answer.
Even though the amount of work involved to make the interface is small, I don't see why you need to call finish() from the Activity that created it. Calling finish() from within the DialogFragment itself will suffice. If you need to send info back with it as well for some reason, you could always call getActivity() and chain a method that exists in the Activity. Ultimately no matter where you call finish, it will detach the Fragment and destroy it.
Just to clarify how to call a method from your Activity in your Fragment
((YourActivity)getActivity()).someMethod(param);
You MUST caste it because Java doesn't know that Activity has whatever method you wanna call. Which ever way you decide to go with, good luck :)
cheers
EDIT
I appreciate your clarification David. In general you are correct. But to be honest in this instance, you are incorrect because of the nature of Fragments and their relationships with the Activity. Again, you will essentially be creating a listener in order to be called by a Fragment that already has an extremely close relationship with the Activity class it is being held by. Any benefits provided by not hardwiring anything through listeners is lost in this case. You will still be rewriting custom code for every Dialog. While in my method you can write a method in the Activity class in such a general way that you only ever have to write it once.
There are only two reasons I see a need to use a Listener:
1. If you are writing code that other people will be using. So you provide an easy way to give info while maintaining a certain structure (like Androids DatePickerDialog).
2. If there is no connection between two parts you are trying to maintain connected (like GUI's in Java).
So I am not trying to say that David is wrong in saying this, and I am grateful he is bringing it up because it is important for people to understand when to use them. But again, in this case the benefits he mentions are non-existent due to the connection between Fragments and the Activity class. Just wanted to clarify why I believe listeners are not necessary here.
Instead of:
.setPositiveButton("Yes.", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//finish() MainActvity
}
})
Use:
.setPositiveButton("Yes.", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// this gets the current activity.
Activity currentActivity = getActivity();
// this finish() method ends the current activity.
currentActivity.finish();
}
})
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;