Reputation: 4257
I am semi-new to android development. I am getting ready to design a project that has a button that has 2 different methods when clicked (effectively a toggle). I know I can do this by implementing OnClickListener myself, but I was wondering if there was a way to make 2 different buttons in the layout xml and then conditionally show one or the other appropriately. Also if this is possible, is it generally a good practice, or is there a better way to have a button perform two different methods? Is it easier overall to just go ahead and implement OnClickListener?
Thanks
(I currently don't have any code to show at the moment, but if my question is vague I'll be happy to elaborate more if necessary)
Upvotes: 2
Views: 3386
Reputation: 12656
I've been thinking about it and if the only difference between the buttons is what they do when clicked, you should use only one button and either:
onClick()
method or click listener to control the behavior, ORbutton.setOnClickListener()
to change the listener when you want to change the behaviorHowever if the buttons are significantly different (e.g. different location ...etc), use my other answer.
Upvotes: 1
Reputation: 12656
Yes it very easy. Put both buttons in your layout XML, and add the attribute android:visibility=GONE
to one of them. In your Java code you can change the visibility of your buttons with button.setView(View.VISIBLE)
and button.setView(View.GONE)
. (Don't use button.setView(View.INVISIBLE) because the button will be invisible but still take up space in the View).
Upvotes: 4