将按钮设置为看起来像 EditText(但行为仍然像按钮)
我意识到这样做有点奇怪,但我有一个按钮需要看起来像一个 EditText 但仍然表现得像一个按钮。我的布局 XML 目前如下所示:
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="?android:attr/editTextStyle" />
这使其具有 EditText 的外观,但也通过阻止触发 onClick 事件(除非按钮具有焦点)(实际上使其需要两次单击)来稍微扰乱行为。有没有办法在不改变按钮行为的情况下保持样式?
我想过只制作一个看起来像 EditText 的九个补丁背景,但有这么多不同的 Android 版本和皮肤,如果可能的话,我宁愿使用系统样式。
I realize this is sort of a weird thing to be doing, but I have a button that needs to look like an EditText but still behave like a button. My layout XML currently looks like this:
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="?android:attr/editTextStyle" />
That gives it the appearance of an EditText, but also messes with the behavior a little bit by preventing the onClick event from being fired unless the button has focus (effectively making it require two clicks). Is there any way to keep the style without changing the button's behavior?
I thought about just making a nine-patch background that looks like an EditText, but with so many different Android versions and skins out there I'd rather use the system style if it's possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一个像按钮一样的 EditText 怎么样?
您也可以为其定义一个 OnClickListener。而且不会获得焦点。
How about an EditText that behaves like a button?
You can define an OnClickListener for it too. And it won't get focus.
如果它绝对需要是一个按钮,您可以向按钮添加一个焦点侦听器,当按钮接收焦点时触发 onclick。
缺点是当按钮通过轨迹球或方向键获得焦点时,点击将会触发。在布局文件中使其不可聚焦:
If it absolutely needs to be a button, you can add a focus listener to your button that fires the onclick when the button receives focus.
The downside is that the click will fire when the button receives focus via a trackball or d-pad. Make it un-focus-able in the layout file:
接受的答案确实允许您将 EditText 样式设置为按钮,但我发现其中存在差异;当您长按它时,它可以让您将文本粘贴到其中,这在用户体验方面非常糟糕。
这就是我将其设置为 EditText 的样式。
The accepted answer does let you style EditText as a button, but I found a discrepancy in it; when you long press on it, it lets you paste text into it which is terrible in terms of UX.
This is what I applied instead to style it as an EditText.