Java sugaring, can I avoid almost duplicating the code here?

private class HSV extends HorizontalScrollView {
    public LinearLayout L;
    public AbsoluteLayout A;
    public HSV(Context context) {
        super(context);
        L = new LinearLayout(context);
        A = new AbsoluteLayout(context);
    }
    @Override public void addView(View child) {
        A.addView(child);
    }
    void update_scroll() {
        removeView(L);
        addView(L, 0);
        L.removeView(A);
        L.addView(A);
        A.invalidate();
        L.invalidate();
        invalidate();
        requestLayout();
    }
    int GetCurrentPos() {
        return getScrollX(); // <-- this line if HSV
        return getScrollY(); // <-- this line if VSV
    }
    ... few more methods skipped, they will not change at all in 'vertical' version
}

I have this class, it does exactly what I want. Now I need a new VSV class that will be inferred from the (vertical) ScrollView and be the same. I can simply copy the entire block and change the HorizontalScrolView extends to expand the ScrollView , and then (L, 0) to (0, L) (oops, this was an error when publishing to SO, of course, this line will not change, GetCurrentPos will be).

or I can add the "bool vertical" property. But Java has no templates or macros or prototypes of the runtime environment, so is there any other way in Java to avoid code duplication in this example?

+5
1

android.widget.ScrollView . widget.HorizontalScrollView, , ,

void addView(View child, int index)

, , . , android.view.ViewGroup. , , -

public abstract class ScrollViewDelegate<T extends FrameLayout> {
  private final T view;
  private LinearLayout L;
  private AbsoluteLayout A;

  public ScrollViewWrapper(T view) {
    this.view = view;
    L = new LinearLayout(view.getContext());   // or pass as parameter
    A = new AbsoluteLayout(view.getContext()); // or pass as parameter
  }

  void update_scroll() {
      view.removeView(L);
      view.addView(L, 0);
      L.removeView(A);
      L.addView(A);
      A.invalidate();
      L.invalidate();
      view.invalidate();
      view.requestLayout();
  }
  // ...
}

HSV/VSV ( ).

public class HSV extends HorizontalScrollView {

  private final ScrollViewDelegate<HorizontalScrollView> delegate;

  public HSV(Context context) {
      super(context);
      this.delegate = new ScrollViewDelegate<HorizontalScrollView>(this);
  }
  // do stuff with this.delegate
}

public class VSV extends ScrollView {

  private final ScrollViewDelegate<ScrollView> delegate;

  public VSV(Context context) {
      super(context);
      this.delegate = new ScrollViewDelegate<ScrollView>(this);
  }
}
+2

All Articles