【发布时间】:2013-12-26 17:02:15
【问题描述】:
为包含图像的颜色选择器创建一个自定义视图,我将在触摸机器人上从此图像中获取颜色,既不会调用 onTouch(View v, MotionEvent ev) 也不会调用 onClick(View v)。
这是我的视图类:
public class ChangeColor extends RelativeLayout {
public ChangeColor(Context context) { super(context); init(); }
public ChangeColor(Context context, AttributeSet attrs) { super(context, attrs); init(); }
private void init(){
LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.change_color, this);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
ImageView iv = (ImageView)findViewById(R.id.colorScaleImageView);
final Bitmap bitmap = ((BitmapDrawable) iv.getDrawable()).getBitmap();
iv.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.d("ImageView", "onClick();");
}
});
iv.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent ev) {
Log.d("ChangeColor", "onTouch();");
switch (ev.getAction()){
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
int c = bitmap.getPixel((int)ev.getX(), (int)ev.getY());
SettingsManager.setColor(c);
Log.d("ChangeColor", "" + c);
return false;
default:
return true;
}
}
});
}
}
和布局xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="@+id/colorScaleImageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/seekBar1"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:clickable="true"
android:layout_gravity="center_horizontal"
android:src="@drawable/background_color" />
<SeekBar
android:id="@+id/seekBar1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/textView1"
android:layout_alignParentLeft="true"
android:focusable="false"
android:maxHeight="8dp"
android:minHeight="8dp"
android:paddingLeft="7dp"
android:paddingRight="7dp"
android:progressDrawable="@drawable/seekbar_progress"
android:thumb="@drawable/seekbar_thumb_"
android:thumbOffset="7dp" />
</RelativeLayout>
因此,LogCat 中不会出现任何日志消息。
附:我在 SO 上看到了一些类似的问题,但它们并没有帮助我。 附言这个视图用在fragment中,fragment用在Activity中。我使用 OnClickListener 在该活动中添加了一个全屏视图,以查看点击是否转到父视图,并且我可以看到来自该背景视图的日志消息,只有在我点击图像外部时,如果我点击图像则没有消息。
谢谢。
【问题讨论】:
-
您不能同时结合 OnClick 和 OnTouch 侦听器。只使用其中之一
-
@GopalRao 我认为你可以两者兼得,只要你不使用 implements 方法。
-
@Fllo “如果你不使用 implements 方法”是什么意思?能不能说的详细点……
-
@GopalRao 这意味着当您像 OlegSemen 那样调用这些方法时,它应该可以工作。但是,当您使用“public class ChangeColor extends RelativeLayout implements OnClickListener, OnTouchListener ...{”时,这会导致这些方法之间发生冲突。也许是错的,但我看过几次,所以现在,我更喜欢 OlegSemen 的方式。
-
@GopalRao 我相信在他们的名单上会被调用。但无论如何,如果我把其中一个拿出来,什么都不会改变。我仍然看不到任何日志消息。
标签: android android-imageview onclicklistener ontouchlistener