前言
最近在使用紋波效果時(shí)遇到了一個(gè)小問(wèn)題,使用RippleDrawable為View控件設(shè)置紋波效果,長(zhǎng)按View控件松開(kāi)之后View的背景色變?yōu)榧y波的顏色,無(wú)法恢復(fù)未點(diǎn)擊控件時(shí)的正常背景色。
首先看兩張紋波的效果圖


首先我們長(zhǎng)按設(shè)置了紋波效果的View控件,正常情況下在紋波效果結(jié)束之后松開(kāi)手指View的背景色會(huì)恢復(fù)成原來(lái)的顏色,而不正常情況下松開(kāi)手指之后背景色并沒(méi)有恢復(fù)。
下面我們看一下紋波異常時(shí)的代碼
- res/drawable-v21/item_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="@color/colorAccent">
<item android:drawable="@color/colorNormalBg"/>
</ripple>
- res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="@+id/test"
android:layout_width="match_parent"
android:layout_height="75dp"
android:layout_margin="16dp"
android:background="@drawable/item_selector"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textColor="#212121"/>
</LinearLayout>
</LinearLayout>
- MainActivity.java
package rich.ivan.rippledrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity implements View.OnClickListener, View.OnLongClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout layout = (LinearLayout) findViewById(R.id.test);
layout.setOnClickListener(this);
layout.setOnLongClickListener(this);
}
@Override
public void onClick(View view) {
}
@Override
public boolean onLongClick(View view) {
view.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_UP:
// intercept touch event
return true;
}
return false;
}
});
return false;
}
}
紋波出現(xiàn)異常的原因
經(jīng)過(guò)我的測(cè)試,發(fā)現(xiàn)了紋波出現(xiàn)異常的原因。在監(jiān)聽(tīng)View長(zhǎng)按事件的同時(shí)監(jiān)聽(tīng)View的觸摸事件,在OnTouchListener的MotionEvent.ACTION_UP事件中返回了true,會(huì)導(dǎo)致紋波松開(kāi)手指之后View無(wú)法恢復(fù)正常的背景色。如果返回false或者使用默認(rèn)的返回操作,紋波效果就能正常顯示。不過(guò)我目前并沒(méi)有搞懂這個(gè)問(wèn)題的原理是什么,還請(qǐng)了解原理的簡(jiǎn)友們指點(diǎn)一下。
異常代碼:
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_UP:
// intercept touch event
return true;
}
正常代碼:
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_UP:
// do not intercept touch event
return false;
}
總結(jié)
使用RippleDrawable創(chuàng)建紋波效果時(shí),如果View既需要監(jiān)聽(tīng)長(zhǎng)按事件又要監(jiān)聽(tīng)用戶(hù)的手勢(shì)操作,在OnTouchListener的onTouch方法中處理手勢(shì)時(shí)如果返回了true,攔截了當(dāng)前的點(diǎn)擊事件,會(huì)造成設(shè)置紋波效果的View控件背景色無(wú)法恢復(fù)正常。