Adding functionality to onClick in Android - android

I want to run a function each time a button is pressed in my app. I know I can make a new button which extends Android's button and override onClick() but I have already made my entire app and want this new functionality as an afterthought. Can I somehow add this functionality without changing the class of all buttons in my app?
Lets say I want to add something like
runthisfunction();
before every onClick() code executes. There are many buttons in various activities and so they have their own onClick functions.
Is there a way that this function is run before each and every onClick() without the need to make a new class and changing all the existing buttons.

Add to your xml resource for whatever button/view you want to have an onClick listener:
android:onClick="fncClick"
For example:
<Button
android:id="#+id/btnClicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="fncClick" />
Then in the activity that utilizes that xml resource, include:
public void fncClick(View view) {
//TODO: Code here
}
This ONLY attaches an onClick listener for this specific button - not all buttons

Related

How can a widely used custom button track which class its onclick is called from?

In my application, I have a custom button that is used in many different custom views.
The behavior differs very slightly depending on which view the button was clicked in, I want to have one #OnClick implementation in my custom button class that takes care of every case in order to avoid having similar code in every custom view class.
Is there a way I can determine in the #OnClick block where the button was clicked from?
It looks something like
public class customButton extends appcompactimagebutton {
//stuff
#OnClick
public void onbuttonclick(){
//handles general behavior
//if (clicked from customViewA) {
//do A stuff
//}
}
}
and then I have customViewA that has a customButton within it, I'm not sure what to put in the if statement, if that's even a proper way to handle something like this
You can use the tag attribute. In your XML layouts, add a line
android:tag="viewname"
to the XML for the button (in code you can do .setTag("viewname"). You can then just modify your onClick to check the tag using this.getTag() and use that to identify where the click came from.

One class for each layout (new page)?

I wast just wondering if the standard practice is to create an activity/fragment class for each layout file (new page).
Example:
MainActivity.java
onCreate(){
setContentView(R.layout.**start_page**)
}
And than when the user clicks a button in the action bar (or some other button on the screen):
onOptionItemSelected() {
switch XX -> case XX: setContentView(R.layout.**next_page**)
}
So could i do the above instead of launching a new activity.java (that contains a new layout.xml) with an intent, or inflating the view with a fragment.java (that also contains a new layout.xml).
I can see that the up/back navigation wouldn't work with the above code, but is that the only reason why you basically have to create two files (.java & .xml) for each new page in your app.
Yes you could do it technically but beware that if you already create an instance of view lets say Button and you change the layout button will be null because button is not located in your View and also it will take time to render again the layout. So it is a best practice to start a new activity or just create a fragment.
You can do that, but every view will be on the given Activity, and the event handlers would be in the same class, which isn't really modular. It could get extremely bloated and you'll have a 2000 line superclass because it handles every single button click in arbitrary functions (or even worse, in a single onClick function).

create common class which includes intents of header and footer icons throughout whole application in android

i stuck with a unusual problem
i have a restaurant application which includes menu icons fixed at the bottom of every layout,
my problem is i dont want to create onsetclicklistner() method of every icon on each of my activity class....
please give some suggestion so that i can make a common class where i can put all my footer icon click event and activities in it and use it on my every activity class with different setcontentview...
hope you all get my question...
looking forward for your reply
You don't need to setup onClickListeners programmatically. You can also put them in the layout XML like this:
<Button android:id="#+id/my_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/my_button_text"
android:onClick="myOnClick"
/>
Then you can declare a base activity class that contains this method in it, like this:
public class BaseActivity extends Activity {
public void myOnClick(View v) {
// Do whatever you want to do when the button is clicked
}
}
Then you write all of your activity classes so that they derive from BaseActivity instead of Activity.

how to change the view of a button onClick in android

In my app I am trying to calculate an operation using timer. For controlling those operations I am using four buttons as Start, Stop, Pause and resume.
But I want to show only 2 buttons. At the beginning I have only two buttons Start and Pause.
When the start button is clicked timer gets started and immediately in Start button's place I want to show the Stop button.
I want to do the same for the other stop and pause buttons. How to do this please help me......
Using ToggleButton is a good solution for you. Do something like:
ToggleButton first = new ToggleButton(getContext());
ToggleButton second = new ToggleButton(getContext());
first.setTextOff("start");
first.setTextOn("stop");
second.setTextOff("pause");
second.setTextOn("resume");
and use setOnCheckedChangeListener() to implement your actions.
In your onClick(View v), v is the button that gets clicked. You can cast it like:
Button b = (Button) v;
so you can change its text with setText(), and set another listener. You can declare the alternate listeners once as members of the activity, and set them without re-declaring them each time.
Your application needs to maintain states, such as "Idle/Stopped", "In Progress", "Paused", etc. If you want to hide buttons, you can use View.setVisibility, and dynamically show and hide the buttons when your state changes (when other buttons are pressed). You would need to set your layout appropriately so that the buttons display nicely as they are shown/hidden dynamically
Or, you can change the text of the buttons, and their associated click listeners dynamically. This method is not very ideal becuase you may run in to cases where you want different amount of buttons for all your different states, and also, you're associating variable behavior with a single control. Also, you must manage your click listeners, adding and removing them dynamically.
here is a simple implementation
public class Demo extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button button=(Button)findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
button.setText("stop");
}
});
}
}
In the main.xml have a Button widget like this,
<Button android:id="#+id/button"
android:text="start"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>

How to simulate a button click using code?

How can I trigger a button click event using code in Android? I want to trigger the button click programmatically when some other event occurs.
Same Problem I am Facing
public void onDateSelectedButtonClick(View v){
/*Something Alarm Management
http://www.java2s.com/Code/Android/Core-Class/Alarmdemo.htm
copied code from this site*/
}
Button code:
<Button
android:onClick="onDateSelectedButtonClick"
android:text="Set notification for this date" />
But I want to call that function OnLoadLayout without OnClickEvent
there is a better way.
View.performClick();
http://developer.android.com/reference/android/view/View.html#performClick()
this should answer all your problems. every View inherits this function, including Button, Spinner, etc.
Just to clarify, View does not have a static performClick() method. You must call performClick() on an instance of View.
For example, you can't just call
View.performClick();
Instead, do something like:
View myView = findViewById(R.id.myview);
myView.performClick();
Just to clarify what moonlightcheese stated:
To trigger a button click event through code in Android
provide the following:
buttonName.performClick();
you can do it this way
private Button btn;
btn = (Button)findViewById(R.id.button2);
btn.performClick();
Just write this simple line of code :-
button.performClick();
where button is the reference variable of Button class and defined as follows:-
private Button buttonToday ;
buttonToday = (Button) findViewById(R.id.buttonToday);
That's it.
Android's callOnClick() (added in API 15) can sometimes be a better choice in my experience than performClick(). If a user has selection sounds enabled, then performClick() could cause the user to hear two continuous selection sounds that are somewhat layered on top of each other which can be jarring. (One selection sound for the user's first button click, and then another for the other button's OnClickListener that you're calling via code.)
Starting with API15, you can use also callOnClick() that directly call attached view OnClickListener. Unlike performClick(), this only calls the listener, and does not do any associated clicking actions like reporting an accessibility event.
If you do not use the sender argument, why not refactor the button handler implementation to separate function, and call it from wherever you want (from the button handler and from the other place).
Anyway, it is a better and cleaner design - a code that needs to be called on button handler AND from some other places deserves to be refactored to own function. Plus it will help you separate UI handling from application logic code. You will also have a nice name to the function, not just onDateSelectedButtonClick().

Categories

Resources