【发布时间】:2019-12-04 22:39:42
【问题描述】:
我正在为电话拨号器构建自定义布局。对于拨号器中的每个号码,我都在使用带有一些 TextView 的 LinearLayout。
问题:当一个onClickListener被设置为自定义LinearLayout并且随后被用户按下时,它卡在按下状态并且不会恢复到状态下的默认项发布时列出。如果我没有为 LinearLayout 设置onClickListener,则状态会正确更改为已按下然后未按下。
通过 Android Studio 的布局检查器调试显示,LinearLayout 在用户释放后仍然有isPressed() == true。我还尝试了 ImageButton 和 Button 而不是 LinearLayout,它表现出类似的行为。应用的主题继承自Theme.MaterialComponents.Light.Bridge。
包含拨号按钮的片段布局:
<TableLayout
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_gravity="center_horizontal"
android:layout_weight="2">
<TableRow
android:layout_height="0px"
android:layout_weight="1"
android:gravity="center">
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:background="#e2e2e2"/>
<DialerButton
android:id="@+id/keypad2"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"/>
...
用于 DialerButton 类的 LinearLayout(它是一个基本类,只是覆盖了 LinearLayout 并扩展了以下布局)如下所示:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:background="@drawable/dialpad_btn_background"
android:clickable="true"
android:focusable="true">
<TextView
android:id="@+id/tvNumeral"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="2"/>
<TextView
android:id="@+id/tvLettering"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="ABC"/>
</LinearLayout>
dialpad_btn_background.xml 如下所示:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@color/dark_grey"/>
<item android:drawable="@color/white"/>
</selector>
将 OnClickListener 附加到 LinearLayout 的代码是标准的:
keypad1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
/// ... Do work ...
}
});
【问题讨论】: