您的位置:首页 > 其它

给TextView的drawableRight属性设置点击事件

2016-11-30 18:15 411 查看
由于需求,要给TextView的drawableRight图片设置点击事件



其实更多的可能是EditText,像登录框那样的,其实都一样

上代码

/**
* Created by great小海海 on 2016/11/30 0030.
* 只是加了右侧图标的点击事件
*/
public class DrawableTextView extends TextView{
public DrawableRightClickListener drawableRightClickListener;

public DrawableTextView(Context context) {
super(context);
}

public DrawableTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}

public DrawableTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}

public DrawableRightClickListener getDrawableRightClick() {
return drawableRightClickListener;
}

public void setDrawableRightClick(DrawableRightClickListener drawableRightClickListener) {
this.drawableRightClickListener = drawableRightClickListener;
}

//为了方便,直接写了一个内部类的接口
public interface DrawableRightClickListener{
void onDrawableRightClickListener(View view);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
if (drawableRightClickListener!=null){
// getCompoundDrawables获取是一个数组,数组0,1,2,3,对应着左,上,右,下 这4个位置的图片,如果没有就为null
Drawable rightDrawable=getCompoundDrawables()[2];
//判断的依据是获取点击区域相对于屏幕的x值比我(获取TextView的最右边界减去边界宽度)大就可以判断点击在Drawable上
if(rightDrawable!=null&&event.getRawX()>=(getRight()-rightDrawable.getBounds().width())){
drawableRightClickListener.onDrawableRightClickListener(this);
}
//此处不能设置成false,否则drawable不会触发点击事件,如果设置,TextView会处理事件
return false;
}

break;

}
return super.onTouchEvent(event);

}


应用很简单

布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"

tools:context="com.example.administrator.textviewdrawable.MainActivity">

<com.example.administrator.textviewdrawable.DrawableTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="点击右边的图片试试"
android:textSize="30sp"
android:layout_centerInParent="true"
android:drawableRight="@mipmap/ic_launcher"
android:id="@+id/draw_tv"/>
</RelativeLayout>


public class MainActivity extends AppCompatActivity {

private DrawableTextView tv;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (DrawableTextView) findViewById(R.id.draw_tv);

tv.setDrawableRightClick(new DrawableTextView.DrawableRightClickListener() {
@Override
public void onDrawableRightClickListener(View view) {
Toast.makeText(MainActivity.this, "已收到点击指令", Toast.LENGTH_SHORT).show();
}
});
}


效果图

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐