7

我意识到这是一件很奇怪的事情,但我有一个按钮需要看起来像一个 EditText 但仍然像一个按钮。我的布局 XML 当前如下所示:

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    style="?android:attr/editTextStyle" />

这使它具有 EditText 的外观,但也通过阻止 onClick 事件被触发,除非按钮具有焦点(有效地使其需要两次单击),从而使行为有点混乱。有没有办法在不改变按钮行为的情况下保持风格?

我想过只制作一个看起来像 EditText 的九个补丁背景,但是有这么多不同的 Android 版本和皮肤,如果可能的话,我宁愿使用系统样式。

4

3 回答 3

30

行为像按钮的 EditText 怎么样?

<EditText android:id="@+id/Edit"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:clickable="true"/>

您也可以为它定义一个 OnClickListener。而且它不会得到焦点。

于 2011-11-28T22:39:45.767 回答
1

如果它绝对需要是一个按钮,您可以向您的按钮添加一个焦点侦听器,该侦听器在按钮接收到焦点时触发 onclick。

weirdoButton.setOnFocusChangeListener(new OnFocusChangeListener() {

  @Override
  public void onFocusChange(View view, boolean hasFocus) {
    if(hasFocus) {
      weirdoButton.performClick();
    }
  }
});

缺点是当按钮通过轨迹球或 d-pad 获得焦点时,点击会触发。在布局文件中使其无法聚焦:

<Button
    android:id="@+id/weirdoButton"
    android:layout_width="match_parent"
    android:layout_height="50dip"
    android:focusable="false"
    style="?android:attr/editTextStyle" />
于 2011-11-28T22:55:30.110 回答
0

接受的答案确实让您将 EditText 设置为按钮,但我发现其中存在差异;当您长按它时,它可以让您将文本粘贴到其中,这在用户体验方面很糟糕。

这就是我将其设置为 EditText 的样式。

<Button
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:textSize="16sp"
    android:focusable="false"
    android:id="@+id/btnAddMember"
    style="?android:attr/editTextStyle"
    android:focusableInTouchMode="false"
    android:clickable="true"
    android:hint="Button Content"/>
于 2016-07-05T07:57:19.500 回答