监听android:drawableLeft和android:drawableRight点击事件
Android官方没有提供对android:drawableLeft和android:drawableRight点击事件的监听,但有些情况下,如下面的搜索栏,
需要在用户输入字符点击左侧的搜索图标后触发搜索事件,而此搜索icon是通过android:drawableLeft添加的,此时就需要对android:drawableLeft上去的icon进行事件监听。我写了一个工具DrawableUtil类,对android:drawableLeft和android:drawableRight进行监听。
import android.graphics.drawable.Drawable;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
public class DrawableUtil {
/**
* TextView四周drawable的序号。
* 0 left, 1 top, 2 right, 3 bottom
*/
private final int LEFT = 0;
private final int RIGHT = 2;
private OnDrawableListener listener;
private TextView mTextView;
public DrawableUtil(TextView textView, OnDrawableListener l) {
mTextView = textView;
mTextView.setOnTouchListener(mOnTouchListener);
listener = l;
}
public interface OnDrawableListener {
public void onLeft(View v, Drawable left);
public void onRight(View v, Drawable right);
}
private View.OnTouchListener mOnTouchListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
if (listener != null) {
Drawable drawableLeft = mTextView.getCompoundDrawables()[LEFT];
if (drawableLeft != null && event.getRawX() <= (mTextView.getLeft() + drawableLeft.getBounds().width())) {
listener.onLeft(v, drawableLeft);
return true;
}
Drawable drawableRight = mTextView.getCompoundDrawables()[RIGHT];
if (drawableRight != null && event.getRawX() >= (mTextView.getRight() - drawableRight.getBounds().width())) {
listener.onRight(v, drawableRight);
return true;
}
}
break;
}
return false;
}
};
}
使用DrawableUtil,在构造时候传递一个OnDrawableListener即可完成监听,如:
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class DrawableActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawable_activity);
TextView textView = findViewById(R.id.text);
DrawableUtil drawableUtil = new DrawableUtil(textView, new DrawableUtil.OnDrawableListener() {
@Override
public void onLeft(View v, Drawable left) {
Toast.makeText(getApplicationContext(), "left", Toast.LENGTH_SHORT).show();
}
@Override
public void onRight(View v, Drawable right) {
Toast.makeText(getApplicationContext(), "right", Toast.LENGTH_SHORT).show();
}
});
}
}
注意要对xml布局中的TextView添加事件属性为true:
android:clickable="true"