Call a method just before OnClick is called - java

I have been looking for my question on Google and inside the forum but I cannot an answer so far. I am using android studio to code an app in Java
The thing is : inside a class, I have overrided the OnClick() method because I have to implement a lot of views.
Now I want to call a function just before OnClick() is called.
What I mean is, for instance, if the user taps on a button, before OnClick() is called I want one of my methods to be called.
Does anyone know how to do this ?
Thank you in advance

I want to call a function just before OnClick() is called
You can use a logic inside onClick() like,
if(userhaspermission())//your method to check if the user has permission
{
//your onclick operation code
}
Make your checking permission method with return type as boolean

Implement your custom OnClickListener as follows
public abstract class MyOnClickListener implements OnClickListener {
#Override
public void onClick(View v) {
//Do common action
if(condidtionSatisfied){
performClick(v);
}
}
public abstract void performClick(View v);
}
Set onClickListener to any component as follows:
button.setOnClickListener(new MyOnClickListener() {
#Override
public void performClick(View v) {
//Execute post click action
}
});
This will ensure your common code will be called for all the views and it would be much cleaner approach.

Override the onClick() method and write your first logic which you want.

Write your own Listener like Sagar said
This logic is quite similar to Sagar's Answers.
Write abstract class as given below
public abstract class OnClick implements View.OnClickListener {
public void beforeClick(View v) {
}
#Override
public void onClick(View v) {
beforeClick(v);
performClick(v);
afterClick(v);
}
public void performClick(View v) {
}
public void afterClick(View v) {
}
}
NOTE : See in above code it implements View.OnClickListener, so this logic will works for views which extends View super class. If you want above logic for object's which needs Dialog interface onClick then you need to modify it for DialogInterface.OnClickListener.
So you can use above logic as below
//Let say you need it for button with id button
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClick() {
#Override
public void beforeClick(View v) {
Toast.makeText(MainActivity.this, "Before", Toast.LENGTH_SHORT).show();
}
#Override
public void performClick(View v) {
Toast.makeText(MainActivity.this, "Click", Toast.LENGTH_SHORT).show();
}
#Override
public void afterClick(View v) {
Toast.makeText(MainActivity.this, "After", Toast.LENGTH_SHORT).show();
}
});

Related

How to create a util that can be referenced multiple times in different activities

I have successfully implemented a custom Dialog box that appears when the user tries to leave an activity via a back button or by using onBackPressed(). They can simply cancel the dialog box or continue, and leave the activity. This function has been implemented in multiple activities, however its making my code a lot longer than it needs to be. I wanted to know how to create a util that can be referenced in different activities, without the need for the chunk of code to copy pasted multiple times. Please note that I am retrieving the dialog title and description from string.xml
This is my code:
Dialog customDialog;
Button button_one, button_two;
TextView dialog_title, dialog_description;
customDialog = new Dialog(this);
//Back button will close app
#Override
public void onBackPressed() {
customDialog.setContentView(R.layout.custom_dialog_box);
dialog_title = customDialog.findViewById(R.id.dialog_title);
dialog_title.setText(getString(R.string.leaving_activity_warning_title));
dialog_description = customDialog.findViewById(R.id.dialog_description); dialog_description.setText(getString(R.string.leaving_activity_warning_description));
button_one = customDialog.findViewById(R.id.button_one);
button_one.setText(getString(R.string.cancel));
button_two = customDialog.findViewById(R.id.button_two);
button_two.setText(getString(R.string.leave_anyway));
button_one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
customDialog.dismiss();
}
});
button_two.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
customDialog.dismiss();
finish();
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
});
Objects.requireNonNull(customDialog.getWindow()).setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
customDialog.show();
}
UPDATE
Created a Java file called "DialogBoxMessage"
DialogBoxMessage Code:
class DialogBoxMessage {
private Dialog customDialog;
private TextView dialog_title, dialog_description;
private Button button_one, button_two;
//Custom Dialog Box Initialization
DialogBoxMessage(Button myButtonOne, TextView myDialogTitle, TextView myDialogDescription, Dialog myCustomDialog) {
customDialog = myCustomDialog;
button_one = myButtonOne;
button_two = myButtonOne;
dialog_title = myDialogTitle;
dialog_description = myDialogDescription;
}
void leaveActivity() {
customDialog.setContentView(R.layout.custom_dialog_box);
dialog_title = customDialog.findViewById(R.id.dialog_title);
dialog_title.setText(Resources.getSystem().getString(R.string.leaving_activity_warning_title));
dialog_description = customDialog.findViewById(R.id.dialog_description);
dialog_description.setText(Resources.getSystem().getString(R.string.leaving_activity_warning_description));
button_one = customDialog.findViewById(R.id.button_one);
button_one.setText(Resources.getSystem().getString(R.string.cancel));
button_two = customDialog.findViewById(R.id.button_two);
button_two.setText(Resources.getSystem().getString(R.string.leave_anyway));
button_one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
customDialog.dismiss();
}
});
button_two.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
customDialog.dismiss();
}
});
Objects.requireNonNull(customDialog.getWindow()).setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
customDialog.show();
}
}
I input the following code in another activity
Other activity code:
//Reusable exit dialog message
DialogBoxMessage dialogBoxMessage;
//Back button will close app
#Override
public void onBackPressed() {
dialogBoxMessage.leaveActivity();
finish();
}
But it doesn't seem to work, I think there are a lot of issues... please help :(
I assume customDialog is a seperate class you wrote - therefore i would suggest you put main information like contentview, title, message or type in the constructor when you initialize ur Dialog.
For your onClick Method I suggest you create an Interface to handle Button Clicks in your
customDialog class.
This could be implemented as a static method in a utilities class. The method would require 'this' as a parameter, which contains the activity context. The method should return the result of the button press. The activity can use this response to determine if finish() should be called or not.
UPDATE
I had suggested a simple static method, but you've gone down the object-oriented route. That's fine.
However, your constructor requires passing in several views, which wouldn't appear to achieve the code efficiency you are after.
Your constructor should just require the Activity context; everything else is encapsulated in your new class.
In each Activity's onBackPressed method you will need to create the object with
dialogBoxMessage = new DialogBoxMessage(this);
before you can call any of that object's methods.

How to Reach Bottom Sheet from another activity?

I tried to use a bottom sheet which use a layout of an activity, not dialog.
[Here is my bottom sheet][1]
But I can't access "Pay Now" button. I tried to use click listener in the same activity, but nothing happens. How can I listen this button and where?
Activity of Bottom Sheet
public class SheetActivity extends AppCompatActivity {
Button sheet_button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sheet);
sheet_button = (Button)findViewById(R.id.sheet_button);
//
sheet_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "Done!", Toast.LENGTH_SHORT).show();
sheet_button.setText("deneme");
}
});
}}
This is generally pretty simple.
If your bottom sheet is a DialogFragment or BottomSheetDialogFrament attach a listener into the onAttach(Context context) method like so:
define the interface in the Fragment:
interface CheckoutButtonListener {
void onClick(/*provide whatever arguments you need to back to parent*/);
}
usage:
// Define the member variable
private CheckoutButtonListener mCheckoutListener;
#Override
public void onAttach(Context context){
super.onAttach(context);
try{
mCheckoutListener = (CheckoutButtonListener) context;
}catch(ClassCastException){
// Handle the error silently or rethrow so usage is expected
}
}
Then when you attach the listener to the button:
mButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
mCheckoutListener.onClick(); // call the interface method
}
});
Finally, implement the interface in whatever Activity is showing the sheet:
class MyActivity extends AppCompatActivity implements CheckoutButtonListener {
//.. other code
// interface method
#Override
public void onClick(){
// do whatever you need to do
}
}
If you are not using a re-usable bottom sheet (i.e as a DialogFragment) then you should include this code in each place you display it, however better to modularize.
Good Luck and Happy Coding!

How to use setOnClickListener to the buttons in android using java [duplicate]

I have trouble understanding this code. I get that findViewById will get the button widget and then it'll cast it. Then, it's going to use the button to call the setOnClickListener method. However, I don't know what is that argument being passed into the setOnClickListener and I have never seen code like that before. How is it that it creates a new object but is able to create a method of its own within another method's argument? Would be great if someone could explain that. Also, what type of object is the setOnClickListener method taking in?
btn = (Button)findViewById(R.id.firstButton);
btn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
tv.setText(months[rand.nextInt(12)]);
tv.setTextColor(Color.rgb(rand.nextInt(255)+1, rand.nextInt(255)+1, rand.nextInt(255)+1));
}
});
It works like this. View.OnClickListenere is defined -
public interface OnClickListener {
void onClick(View v);
}
As far as we know you cannot instantiate an object OnClickListener, as it doesn't have a method implemented. So there are two ways you can go by - you can implement this interface which will override onClick method like this:
public class MyListener implements View.OnClickListener {
#Override
public void onClick (View v) {
// your code here;
}
}
But it's tedious to do it each time as you want to set a click listener. So in order to avoid this you can provide the implementation for the method on spot, just like in an example you gave.
setOnClickListener takes View.OnClickListener as its parameter.
This is the best way to implement Onclicklistener for many buttons in a row
implement View.onclicklistener.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
This is a button in the MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt_submit = (Button) findViewById(R.id.submit);
bt_submit.setOnClickListener(this);
}
This is an override method
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.submit:
//action
break;
case R.id.secondbutton:
//action
break;
}
}
That what manual says about setOnClickListener method is:
public void setOnClickListener (View.OnClickListener l)
Added in API level 1 Register a callback to be invoked when this view
is clicked. If this view is not clickable, it becomes clickable.
Parameters
l View.OnClickListener: The callback that will run
And normally you have to use it like this
public class ExampleActivity extends Activity implements OnClickListener {
protected void onCreate(Bundle savedValues) {
...
Button button = (Button)findViewById(R.id.corky);
button.setOnClickListener(this);
}
// Implement the OnClickListener callback
public void onClick(View v) {
// do something when the button is clicked
}
...
}
Take a look at this lesson as well Building a Simple Calculator using Android Studio.
its an implementation of anonymouse class object creation to give ease of writing less code and to save time
It works by same principle of anonymous inner class where we can instantiate an interface without actually defining a class :
Ref: https://www.geeksforgeeks.org/anonymous-inner-class-java/

Call method from another object-java

I'm doing some Android development and I have an object, which doing a specific task. When that task is done I need to inform my main method (Main Activity), which is constantly running, that the process has been finished and pass some information about it.
This may sound a bit unclear, so I'll give you an example:
Take a look at the setOnClickListener() method in Android:
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
//This method is called on click
#Override
public void onClick(View v) {
//The View is passed in an anonymous inner class
}
});
It waits for a button to be clicked and calls the onClick(View v) method. I am seeking to achieve the same code structure. How to do this?
You mentioned "process". If you are truly doing something in a different process, then you need to look at interprocess communications (IPC). Otherwise, you can use an interface:
Create a class called MyListener:
public interface MyListener {
void onComplete();
}
In your class that will notify your activity:
MyListener myListener;
public void setMyListener(MyListener myListener){
this.myListener = myListener;
}
Then, when you are ready to notify your main activity, call this line:
myListener.onComplete();
Last, in your MainActivity implement MyListener:
public class MyListener extends Activity implements MyListener {
///other stuff
#Override
public void onComplete(){
// here you are notified when onComplete it called
}
}
Hope this helps. Cheers.
This is exactly Listener pattern that you use with views in android. What you want to do is declare an interface in your class that's doing the job, and pass an instance of this interface. Raw example:
TaskDoer.java:
public class TaskDoer {
public interface OnTaskDoneListener {
void onDone(Data data);
}
public void doTask(OnTaskDoneListener listener) {
// do task...
listener.onDone(data);
}
}
Activity:
public void doTaskAndGetResult() {
new TaskDoer().doTask(new TaskDoer.OnTaskDoneListener() {
public void onDone(Data data) {
// do something
}
}
}

CWAC-Camera Take Photo on touch screen

I've tried implementing an onClickListener on a CameraFragment, however, it never seems to be called. I am probably missing something quite simple. Does anyone have any ideas?
public class CWACCameraFragment extends CameraFragment implements OnClickListener {
//...
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
takePicture();
Toast.makeText(getActivity(),"click",
Toast.LENGTH_LONG).show();
}
Is there a way to ensure that the onClick event occurs?
In the demo app, I added the following to DemoCameraFragment:
#Override
public void onStart() {
super.onStart();
getView().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e(getClass().getSimpleName(), "got here");
}
});
}
Log messages showed up just fine. Hence, AFAICT, your approach works, so perhaps there is some bug in how you wired in the click listener.

Categories

Resources