简体   繁体   English

扩展android View类并影响所有子类

[英]Extend android View class and affect all sub classes

I need to extends View class in Android in order to override couple of methods. 我需要在Android中扩展View类,以便重写几个方法。

public class ExtendedView extends View {

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

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_MOVE && getParent() != null) 
            getParent().requestDisallowInterceptTouchEvent(true);
        return super.onTouchEvent(event);
    }

     ...
}

There are couple of view type in android which derive from View such as ImageView and etc. android中有几种视图类型是从View派生的,例如ImageView等。

They do not access to overridden methods in ExtendedView class. 他们无法访问ExtendedView类中的重写方法。

One solution is creating extended classes for all of them such as : 一种解决方案是为其创建扩展类,例如:

public class ExtendedImageView extends ImageView

And override the methods. 并重写方法。

But is there any better solution to avoid such a code redundancy? 但是,有没有更好的解决方案来避免这种代码冗余呢?

Create a BaseActivity implementing onTouchEventListener (or something like that, dont remember), then when you have a view which requires to handle it, just setOnTouchListener(this) 创建一个实现onTouchEventListener的BaseActivity(或类似的东西,不记得了),然后当您有一个需要处理它的视图时,只需setOnTouchListener(this)

Of course, make your activities extend BaseActivity 当然,使您的活动扩展BaseActivity

Regards 问候

As per me this is simple and decent way. 按照我的看法,这是简单而体面的方式。 Here, your code is centralized and one common implementation is given which all intended ExtendedView classes will use. 在这里,您的代码是集中的,并给出了一个通用的实现,所有预期的ExtendedView类都将使用该实现。

class MyImplementation
{
 public boolean methodA(View v, MotionEvent event)
 {
  boolean someBoolean = false;
  // some impl of your spl method.
  if(v instanceOf ExtendedImageView)
   {
     // ImageView called this method.
   }

 }
 return someBoolean;
}

Image View implementation 影像检视实作

public class ExtendedImageView extends ImageView{
    public boolean onTouchEvent (MotionEvent event)
     {
       MyImplementaion a  = new MyImplemenation();
       boolean b = a.methodA(this, event);
       return b;
     }
}

For Some other View 对于其他观点

public class ExtendedMapView extends MapView{

       public boolean onTouchEvent (MotionEvent event)
       {
        MyImplementaion a  = new MyImplemenation();
        boolean b = a.methodA(this, event);
        return b;
       }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM