0

我创建了自己的小部件,一个带有 TextView(标签)和 Spinner 的 LinearLayout。

在 XML 中看起来像这样:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:orientation="horizontal"
    android:clickable="true"
    android:focusable="true"
    android:focusableInTouchMode="true"
    style="@style/MySpinner>
    <TextView android:id="@+id/label"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textStyle="bold"
        android:layout_weight="0.4"
        android:textSize="18sp"
        android:padding="8dp"
        android:enabled="false"/>
    <Spinner android:id="@+id/spinner"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:entries="@array/thats_me_age_values"
        android:layout_weight="0.6"
        android:spinnerMode="dialog"
        android:padding="8dp"/>
</LinearLayout>

LinearLayout 应该获取所有触摸事件,以便它可以正确使用它的样式(按下时背景更改)。该样式将背景属性设置为此选择器:

<?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android">
     <!-- pressed -->
     <item android:state_pressed="true" android:state_focused="false"> 
         <shape android:shape="rectangle" android:visible="true">
             <corners android:topLeftRadius="7dp" android:topRightRadius="7dp"/>
             <solid android:color="@color/dark_yellow"/>
             <stroke android:width="1dp" android:color="@color/grey"/>
         </shape>
     </item> 
     <!-- focused -->
     <item android:state_focused="true"> 
         <shape android:shape="rectangle" android:visible="true">
             <corners android:topLeftRadius="7dp" android:topRightRadius="7dp"/>
             <solid android:color="@color/dark_yellow"/>
             <stroke android:width="1dp" android:color="@color/grey"/>
         </shape>
     </item> 
     <!-- default -->
     <item>
         <shape android:shape="rectangle" android:visible="true">
             <corners android:topLeftRadius="7dp" android:topRightRadius="7dp"/>
             <solid android:color="@color/yellow"/>
             <stroke android:width="1dp" android:color="@color/grey"/>
         </shape>
     </item>
 </selector>

我已经尝试为 LinearLayout 覆盖 onInterceptTouch 方法。日志消息在按下时显示,但背景不会改变。

@Override
public boolean onTouchEvent(MotionEvent event) {
    Log.i("TOUCH", "onTouchEvent");
    return super.onTouchEvent(event);
}

@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
    onTouchEvent(ev);
    Log.i("TOUCH", "onInterceptTouchEvent");
    return false;
}
4

1 回答 1

0

我认为将 android:addStatesFromChildren="true" 添加到 LinearLayout 将解决您的问题......因此,当您单击/聚焦时,您的微调器线性布局会将其状态更改为单击/聚焦。

于 2013-01-24T14:10:16.670 回答