有条件显示的视图和布局元素
我是 Android 开发的半新手。我正准备设计一个项目,该项目有一个按钮,单击时有两种不同的方法(实际上是一个切换)。我知道我可以通过自己实现 OnClickListener 来做到这一点,但我想知道是否有一种方法可以在布局 xml 中创建 2 个不同的按钮,然后有条件地适当地显示一个或另一个。另外,如果这是可能的,这通常是一个好的做法,还是有更好的方法让按钮执行两种不同的方法?总体而言,继续实施 OnClickListener 是否更容易?
谢谢
(我目前没有任何代码可以显示,但如果我的问题含糊不清,我很乐意在必要时详细说明)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,这很容易。将两个按钮放入布局 XML 中,并将属性
android:visibility=GONE
添加到其中一个按钮。在 Java 代码中,您可以使用button.setView(View.VISIBLE)
和button.setView(View.GONE)
更改按钮的可见性。 (不要使用button.setView(View.INVISIBLE),因为按钮将不可见,但仍占用视图中的空间)。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 withbutton.setView(View.VISIBLE)
andbutton.setView(View.GONE)
. (Don't use button.setView(View.INVISIBLE) because the button will be invisible but still take up space in the View).我一直在考虑这个问题,如果按钮之间的唯一区别是它们在单击时执行的操作,那么您应该只使用一个按钮,并且:
onClick()
方法中使用 if/else 或单击侦听器来控制行为,或者button.setOnClickListener()
来更改侦听器但是,如果按钮显着不同(例如不同的位置...等),请使用我的另一个答案。
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.