I have a class called AlertDialogFragment that will be used to create an alert dialog when needed throughout my program. The fragment that creates the dialog will call a function if the positive button is clicked or nothing if the negative button is clicked. Im fairly new to android development and any tips or help is appreciated.
Here is my AlertDialogFragment:
class AlertDialogFragment : DialogFragment() {
companion object {
private val TAG = "AlertDialogFragment"
fun newInstance(message: String, positiveBtnText: String, negativeBtnText: String): AlertDialogFragment {
val fragment = AlertDialogFragment()
fragment.isCancelable = false
val args = Bundle()
args.putString("aMessage", message)
args.putString("aPositiveBtnText", positiveBtnText)
args.putString("aNegativeBtnText", negativeBtnText)
fragment.arguments = args
return fragment
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
Log.d(TAG, "onCreateDialog called")
super.onCreateDialog(savedInstanceState)
return activity?.let {
val builder = AlertDialog.Builder(it)
builder.setMessage(arguments?.getString("aMessage"))
.setPositiveButton(arguments?.getString("aPositiveBtnText"), DialogInterface.OnClickListener { dialog, id ->
Log.d(TAG, "Yes!")
})
.setNegativeButton(arguments?.getString("aNegativeBtnText"), DialogInterface.OnClickListener { dialog, id ->
Log.d(TAG, "Dismiss!")
})
Log.d(TAG, "onCreateDialog ending")
builder.create()
} ?: throw IllegalStateException("Activity can not be null")
}
}
Here is my attempt to initialize the alert dialog and set the target fragment:
try {
AlertDialogFragment alertDialogFragment = new AlertDialogFragment().Companion.newInstance(
"Would you like to continue?",
"Yes",
"Dismiss");
alertDialogFragment.setTargetFragment(this, TARGET_FRAGMENT_REQUEST_CODE);
alertDialogFragment.show(getActivity().getSupportFragmentManager(), "dialog");
}catch (Exception e){
e.printStackTrace();
}
Thanks in advance for any help!
EDIT: I am using kotlin for the alert dialog and the fragment that initializes it, is in java.
You can retrieve the target fragment and request code you passed in and then use that to call onActivityResult:
targetFragment?.let { fragment ->
fragment.onActivityResult(fragment.targetRequestCode, Activity.RESULT_OK, null)
}
and in your function:
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
Log.d(TAG, "onCreateDialog called")
super.onCreateDialog(savedInstanceState)
return activity?.let {
val builder = AlertDialog.Builder(it)
builder.setMessage(arguments?.getString("aMessage"))
.setPositiveButton(arguments?.getString("aPositiveBtnText"), DialogInterface.OnClickListener { dialog, id ->
Log.d(TAG, "Yes!")
targetFragment?.let { fragment ->
fragment.onActivityResult(fragment.targetRequestCode, Activity.RESULT_OK, null)
}
})
.setNegativeButton(arguments?.getString("aNegativeBtnText"), DialogInterface.OnClickListener { dialog, id ->
Log.d(TAG, "Dismiss!")
})
Log.d(TAG, "onCreateDialog ending")
builder.create()
} ?: throw IllegalStateException("Activity can not be null")
}
In your launching fragment you override onActivityResult and handle the returned value.
Note that if your fragment is recreated, you will have to re-assign the target fragment.
Related
I have an app that uses tabbed activity, with 3 tabs, each with a separate fragment and layout. Tab3 has some user-profile settings, like a name for example. Name is displayed inside a cardview, so I made that cardview clickable, and onClick it would open an alertDialog with an edit text to enter the name. to build this dialog I found 2 methods.
First:- (this is run once the cardview is clicked(On clicklistener)) and its working very well and I have no issues with it but it just doesn't feel like a best-practice
AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
alert.setTitle("Enter your Username");
LayoutInflater inflater = getActivity().getLayoutInflater();
View view1 = inflater.inflate(R.layout.editname_layout, null);
alert.setView(view1);
final EditText input = view1.findViewById(R.id.editname);
alert.setPositiveButton("Save", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
textView.setText(input.getText().toString());
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
Second:- is that I build a separate DialogFragment with an interface to send data back to fragment this one feels like a best practice but i have faced many issues with it, such as.. when data is sent back to my fragment, I can't use the method "textView.setText" on the received data as I receive it outside the onCreateView method and thus textView always returns null.
public class Dialog extends AppCompatDialogFragment {
private Context context;
public DialogListener listener;
public Dialog(Context context) {
this.context = context;
}
#NonNull
#Override
public android.app.Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.name_layout, null);
final EditText name = (EditText) view.findViewById(R.id.editname);
builder.setView(view)
.setTitle("Username")
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String text = name.getText().toString();
listener.data(text);
Toast.makeText(getActivity(), "Saved", Toast.LENGTH_SHORT).show();
}
});
return builder.create();
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
try {
Fragment fragment = new Tab3();
listener = (DialogListener) fragment;
}
catch (ClassCastException e) {
throw new ClassCastException(context.toString() + " must implement d.l");
}
}
public interface DialogListener {
void data(String name);
}
}
So what I'm thinking is that I should go with the first method as it's easier, and it's easier to extract text from it but still not sure if it would be a good practice.
thanks in advance!
Prefer second solution:
You can have your custom UI elements.
You have access to lifecycle changes (onResume,onCreate,etc.).
It keeps showing even when orientation is changed (the first solution doesn't).
And for sending data to previous fragment you can create listener to fragment.
interface MyFragmentListener {
fun onSendBackData(data: Any)
}
class MyFragment:Fragment {
private var listener: MyFragmentListener? = null
override fun onAttach(context: Context) {
super.onAttach(context)
listener = when {
context is MyFragmentListener -> context
parentFragment is MyFragmentListener -> parentFragment as MyFragmentListener
else -> error("You should implement MyFragmentListener")
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
button.setOnClickListener {
listener?.onSendBackData("Data")
}
}
}
class Activity : Activity(), MyFragmentListener {
override fun onSendBackData(data:Any) {
textView.text = data.toString()
}
}
It's not a question of best practice, it's just how you want to design your App.
The first solution: You can directly interact with your UI. e.g: Set the new value in textView. But if you write a lot of dialogs, think about to generify the logic (the second solution).
The second solution: If you want just a generic Dialog, you need the use-case for it = multiple calls for dialogs and don't forget: if you instantiate the Dialog class you need to give him the textView if you want to change it in the UI
I got a very strange exception while using Sharedpreferences and DialogFragment:
Unable to start activity ComponentInfo{com.example.barta1.site_patrol/com.example.barta1.site_patrol.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method
'void android.app.Dialog.setOwnerActivity(android.app.Activity)'
on a null object reference -
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2679)
I really do not have a clue what causes this error, but after this happened, I never be able to start
my application again, it continuosly crashed with the same exception above. The MainActivity is my launching activity in my application with a DialogFragment attached which I use to login users. I show this dialogfragment if the users not logged in (the "logged in" status saved in a sharedpreference object).
My MainActivity is like this:
public class MainActivity extends AppCompatActivity implements LoginDialogFragment.NoticeDialogListener {
//...
private LoginDialogFragment dialogFragment;
SharedPreferences pref;
SharedPreferences.Editor edit;
//...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pref = getSharedPreferences("Globals", MODE_PRIVATE);
edit = pref.edit();
boolean isloggedin = pref.getBoolean("Loggedin", false);
if (!isloggedin) {
//if not logged in show the login dialog
showLoginDialog();
}
else {
//... doing some network calls...
}
}
public void showLoginDialog() {
dialogFragment = new LoginDialogFragment();
dialogFragment.show(getFragmentManager(), "LoginDialogFragment");
}
/***
* Network calls if dialog dismissed
* Login dialog can only be closed if logging in is successful
* (if loginname and password matches).
*/
#Override
public void onDismiss() {
//... some network related jobs
}
}
And here is the fragment class:
public class LoginDialogFragment extends DialogFragment {
public interface NoticeDialogListener{
void onDismiss();
}
NoticeDialogListener mListener;
Activity activity;
AlertDialog dialog;
SharedPreferences pref;
SharedPreferences.Editor edit;
#Override
public void onAttach(Context context) {
super.onAttach(context);
try{
activity = (Activity) context;
mListener = (NoticeDialogListener) activity;
pref = activity.getSharedPreferences("Globals", MODE_PRIVATE);
edit = pref.edit();
} catch (ClassCastException e){
throw new ClassCastException(activity.toString() + "must implement NoticeDialogListener");
}
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
String username = pref.getString("Username", null);
if(username==null) {
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.dialog_signin, null);
final AutoCompleteTextView actv_username = view.findViewById(R.id.username);
final EditText password = view.findViewById(R.id.password);
dialog = new AlertDialog.Builder(new ContextThemeWrapper(getContext(), R.style.AlertDialogCustom))
.setView(view)
.setTitle("Bejelentkezés")
.setPositiveButton("OK", null)
.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialogInterface) {
final Button button = ( dialog).getButton(AlertDialog.BUTTON_POSITIVE);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String passw = password.getText().toString();
String user = actv_username.getText().toString();
try {
if (user.length() < 4 || passw.length() < 4) {
Toast.makeText(getContext(), "Too short user/pass.", Toast.LENGTH_SHORT).show();
dialog.show();
} else {
//login to account, if success dismiss.
login(user, passw, dialog);
}
} catch (Exception e) {
e.printStackTrace();
}
// dialog.dismiss();
}
});
}
});
dialog.setCanceledOnTouchOutside(false);
// set the DialogFragment to make the dialog unable to dismiss with back button
// (because not working if called on the dialog directly)
this.setCancelable(false);
return dialog;
} // end of - if username == null.
return null;
}
public void login(final String username, String password, final AlertDialog dialog){
//... some network call
//... if successful:
// edit.putString("Username", username);
// edit.commit();
// edit.putBoolean("Loggedin", true);
// edit.commit();
// dialog.dismiss();
// dialog.setOnShowListener(null);
//
// else
// Toast.makeText(getContext(),"Wrong login credentials",
// Toast.LENGTH_SHORT).show();
}
#Override
public void onDismiss(DialogInterface dialog) {
mListener.onDismiss();
dismissAllowingStateLoss();
}
After reinstalling the package, I could not recreate this exception (even when I killed app process, and start it from the recent apps), end users somehow managed to do this and that time, restarting the application was an instant crash (see the exception above.). It looks like parent activity becomes null somehow ( possible after saving the state and after cannot recover).
How to avoid this in the future? Is there a simple way to deal with this situation?
It would be also a great help if someone can explain to me when this "setOwnerActivity(Activity activity)" from the android library called, that way maybe I can identify what went wrong.
Thanks for any help.
As Mike M. stated out,
You cannot return null from onCreateDialog(). That's too late to be canceling or aborting the Dialog showing.
And the username check before creating the fragment will obviously solve the problem. Also, the LoggedIn field looks redundant now.
I want to finish the activity when custom dialog is cancelled or dismissed. But when I use .setOnDismissListener in other classes, it is never being reached inside. I've found several problems, but the solution was to override onDismiss method inside the customDialog class. But I do not need to override onDismiss method for every customDialog I create. What should I do?
This is the code I call in another class, but never receive message in log "setOnDismissListener".
customDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
Log.d(TAG, "setOnDismissListener");
}
});
My CustomDialog class:
public class CustomDialog extends Dialog {
private static final String TAG = "CustomDialog";
public CustomDialog(Context context, String title, String message) {
super(context);
TextView textView = new TextView(context);
textView.setGravity(Gravity.CENTER);
textView.setPadding(10, 50, 10, 10);
textView.setText(title);
textView.setTextColor(Color.BLACK);
textView.setTextSize(20);
Typeface boldTypeface = Typeface.defaultFromStyle(Typeface.BOLD);
textView.setTypeface(boldTypeface);
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder
.setCustomTitle(textView)
.setMessage(message)
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog customDialog = builder.show();
TextView messageText = customDialog.findViewById(android.R.id.message);
if (messageText != null) {
messageText.setGravity(Gravity.CENTER);
messageText.setTextColor(Color.GRAY);
} else {
Log.w(TAG, "messageText is null");
}
}
}
Yeah, so if you are not using some API to parse information, or are using local variables I suggest you do whatever functionality you want to do in your onClickListener() Method.
The problem is that you are using your CustomDialog which itself extends the Dialog Class. But instead of using that you create a new alert dialog and build that. You dismiss it, but the dialog which is dismissed is not your custom dialog class, but the builder dialog you created in your constructor. Even if you fixed for that, it introduces unnecessary complications.
What I suggest you do is create the Intent in your onClickListener() function. The way to do that would be to change your constructor to support a callback listener. Simply put you cannot just add an onDismissListener() when the dialog you listen to is another one. What you can do is pass in the function that you want to do when the user dismisses the dialog as a special case. See below.
So, first, modify your constructor like this:
public CustomDialog(Context context, String title, String message,
DialogInterface.OnClickListener listener) {
super(context);
}
In your constructor paste your previous code:
TextView textView = new TextView(context);
textView.setGravity(Gravity.CENTER);
textView.setPadding(10, 50, 10, 10);
textView.setText(title);
textView.setTextColor(Color.BLACK);
textView.setTextSize(20);
Typeface boldTypeface = Typeface.defaultFromStyle(Typeface.BOLD);
textView.setTypeface(boldTypeface);
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder
.setCustomTitle(textView)
.setMessage(message)
.setPositiveButton("Ok", listener);
AlertDialog customDialog = builder.show();
TextView messageText = customDialog.findViewById(android.R.id.message);
if (messageText != null) {
messageText.setGravity(Gravity.CENTER);
messageText.setTextColor(Color.GRAY);
} else {
Log.w(TAG, "messageText is null");
}
What you do is where you used to create a new onClickListener() you pass in the listener parameter.
Go to your MainActivity or where you create your custom dialog. There do this:
CustomDialog customDialog = new CustomDialog(FirstActivity.this, "Title", "Message",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Do your functionality here.
Intent intent = new Intent(context, activity.class);
//Add any flags if you want
...
context.startActivity(intent);
//Or you can simply do context.finish();
}
});
When you don't want to pass a onClickListener()(meaning when you don't want to finish() the activity) pass in null.
It would work. If this is not what you wanted, tell me and I will fix it.
Make an interface like
interface OnUserInformedCallback {
fun positive()
fun negative()
}
and implement this in your activity and pass it to the dialog method from where you are gettingdialog and you will get callback of ok and cancle in you activity.
code is like that
fun alertDialog(
context: Context,
message: String,
positiveText: String,
isUa: Boolean,
callback: OnUserInformedCallback
): Dialog {
val dialog = Dialog(context, android.R.style.Theme_Translucent_NoTitleBar)
dialog.setContentView(R.layout.alert_dialog_layout)
dialog.window?.setGravity(Gravity.CENTER)
dialog.setCancelable(true)
dialog.setCanceledOnTouchOutside(true)
val tvOk: TextView = dialog.findViewById(R.id.visit)
val tvMsg: TextView = dialog.findViewById(R.id.mess)
tvMsg.text = message
tvOk.text = positiveText
dialog.findViewById<TextView>(R.id.cancel).setOnClickListener {
callback.negative()
}
tvOk.setOnClickListener {
callback.positive()
}
dialog.create()
return dialog
}
in java for default dialog
private AlertDialog getDialog(Activity context, String message, OnUserInformedCallback callbac) {
return new AlertDialog.Builder(context)
.setTitle(R.string.app_name).setMessage(message)
.setCancelable(true)
.setPositiveButton(android.R.string.yes, (dialog12, which) -> callbac.positive())
.setNegativeButton(android.R.string.yes, (dialog1, which) -> callbac.positive())
.create();
}
I'm using PreferenceFragmentCompat to display and set SharedPreferences. This all works fine. However, I keep getting "W/InputEventReceiver: Attempted to finish an input event but the input event receiver has already been disposed." in my logs, because the standard dialog used by PreferencesFragmentCompat does not seem to use the .setCancelable(false) in its showDialog method. I guess I could build my own custom dialog, but that seems a bit of an overkill just to solve this one small problem. Is there any way to simply overwrite the method?
Update:
It was enough to add this to my PreferencesFragmet (removed MultiSelectListPreferenceDialogFragmentCompat, as I don't use it)
#Override
public void onDisplayPreferenceDialog(Preference pref) {
DialogFragment dialogFragment = null;
String DIALOG_FRAGMENT_TAG = "androidx.preference.PreferenceFragment.DIALOG";
if (pref instanceof EditTextPreference) {
dialogFragment = EditTextPreferenceDialogFragmentCompat.newInstance(pref.getKey());
} else if (pref instanceof ListPreference) {
dialogFragment = ListPreferenceDialogFragmentCompat.newInstance(pref.getKey());
}
if (dialogFragment != null) {
dialogFragment.setTargetFragment(this, 0);
dialogFragment.setCancelable(false); //adding this!
if (this.getFragmentManager() != null) {
dialogFragment.show(this.getFragmentManager(), DIALOG_FRAGMENT_TAG);
}
} else {
super.onDisplayPreferenceDialog(pref);
}
}
I sorted though PreferenceFramgnetCompat source code to solve this issue.
Unfortunately, you can't execute '.setCancelable(false)' to dialog without callback or override.
I'll explain it with callback.
You should implement 'PreferenceFragmentCompat.OnPreferenceDisplayDialogCallback' interface on activity which contains PreferenceFragmentCompat fragment.
When user press a preference one of EditTextPreference, ListPreference or AbstractMultiSelectListPreference, the onPreferenceDisplayDialog method will be executed.
When onPreferenceDisplayDialog method is executed, you should open dialog.
Fortunately, there are three type dialog and Google provide it by public so you don't need to make a custom dialog for them.
Just create instance of dialog and call setCancelable(false) and show it!
Please refer below codes.
class SettingsActivity : FragmentActivity(), PreferenceFragmentCompat.OnPreferenceDisplayDialogCallback {
private val DIALOG_FRAGMENT_TAG = "android.support.v7.preference.PreferenceFragment.DIALOG"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
supportFragmentManager.beginTransaction()
.replace(android.R.id.content, SettingsFragment(), "setting_fragment").commit()
}
override fun onPreferenceDisplayDialog(caller: PreferenceFragmentCompat, preference: Preference?): Boolean {
// check if dialog is already showing
if (supportFragmentManager!!.findFragmentByTag(DIALOG_FRAGMENT_TAG) != null) {
return true
}
val f: DialogFragment
if (preference is EditTextPreference) {
f = EditTextPreferenceDialogFragmentCompat.newInstance(preference.getKey())
} else if (preference is ListPreference) {
f = ListPreferenceDialogFragmentCompat.newInstance(preference.getKey())
} else if (preference is AbstractMultiSelectListPreference) {
f = MultiSelectListPreferenceDialogFragmentCompat.newInstance(preference.getKey())
} else {
throw IllegalArgumentException("Tried to display dialog for unknown " + "preference type. Did you forget to override onDisplayPreferenceDialog()?")
}
f.setTargetFragment(supportFragmentManager.findFragmentByTag("setting_fragment"), 0)
f.isCancelable = false // !! HERE !!
f.show(supportFragmentManager!!, DIALOG_FRAGMENT_TAG)
return true
}
}
I want to know how to add multiple click events to buttons defined in XML, as previously, in Java, we implemented View.onClickListener interface and did the rest of the work in onClick method.
Example:
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.oneButton:
// do your code
break;
case R.id.twoButton:
// do your code
break;
case R.id.threeButton:
// do your code
break;
default:
break;
}
}
I'm making a basic calculator app with the new Kotlin but it seems Kotlin has no such provisions, instead my code looks too long and verbose, as I'm attaching events to all buttons individually.
Can someone tell me how to do the same way in Kotlin? Thanks
For multiple onClickListeners in kotlin (version:1.1.60), the following helped me. Hope it'll be useful to someone else too.
Implement OnClickListener to activity like:
class YourActivity : AppCompatActivity(), View.OnClickListener
set your button in onCreate():
val button = findViewById<Button>(R.id.buttonId)
and assign onclick to the button in onCreate():
button.setOnClickListener { onClick(button) }
and in the override method of onClick() :
override fun onClick(v: View) {
when (v.id) {
R.id.buttonId -> { //your code }
..
..
..
else -> { //your code }
}
}
Yes, in Kotlin you can do it like this:
view.setOnClickListener(object : View.OnClickListener {
override fun onClick(v: View?) {
when(v?.id) {
R.id.imgBack -> {/* do your code */}
R.id.twoButton -> {/* do your code */}
R.id.threeButton -> {/* do your code */}
else -> {/* do your code */}
}
}
}
You can try this following code:
class Testing:AppCompatActivity(), View.OnClickListener {
private val mButton1:Button
private val mButton2:Button
protected fun onCreate(savedInstanceState:Bundle) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_testing)
mButton1 = findViewById(R.id.btn_click) as Button
mButton2 = findViewById(R.id.btn_click1) as Button
mButton1.setOnClickListener(this)
mButton2.setOnClickListener(this)
}
fun onClick(view:View) {
when (view.getId()) {
R.id.btn_click -> {
Toast.makeText(this, "button 1", Toast.LENGTH_SHORT).show()
}
R.id.btn_click1 -> {
Toast.makeText(this, "button 2", Toast.LENGTH_SHORT).show()
}
else -> {}
}
}
}
I hope this is help you.
First of all implement OnClickListener in your Activity, like
class MainActivity : Activity , OnClickListener
then override its implementation like
func onClick(v:View) {
//use when here like
case R.id.youview -> {
// do your work on click of view
}
Don't forgot to set clicklistener on your View.
yourView.setOnClickListener(this)
Or for better understanding go step by step -
Implement OnClickListener in your Activity.
Compiler will ask you to implement overrided methods. Implement those.
Copy paste your java code which you wrote inside onClick method, that can be converted by kotlin itself or write down when conditions.
This code worked for me:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
imgBack.setOnClickListener(this)
twoButton.setOnClickListener(this)
threeButton.setOnClickListener(this)
}
override fun onClick(view:View) {
when (view.id) {
R.id.imgBack -> {
Toast.makeText(this, "imgBack", Toast.LENGTH_SHORT).show()
}
R.id.twoButton -> {
Toast.makeText(this, "twoButton", Toast.LENGTH_SHORT).show()
}
else -> {}
}
}
Don't forget implement View.OnClickListener in your class.
you can create anonymous object from an inteface View.ClickListener and pass it to setOnClickListener function
private val clickListener = View.OnClickListener { p0 ->
when (p0.id) {
....
}
}
... setOnClickListener(clickListener)
Try below like this.
public class MainActivity extends Activity implements View.OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button xyz = (Button) findViewById(R.id.xyz);
xyz.setOnClickListener(this);
}
#Override
public void onClick(View v) {
}}
More detailed information at https://androidacademic.blogspot.in/2016/12/multiple-buttons-onclicklistener-android.html