将click事件传递给Android微调器

时间:2013-01-17 23:37:43

标签: android

我创建了自己的小部件,带有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应该获取所有触摸事件,以便它可以正确使用它的样式(按下时背景更改)。样式将background属性设置为此选择器:

<?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;
}

1 个答案:

答案 0 :(得分:0)

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