我正在尋求減少Android項目中的冗餘代碼。讓我告訴你我已經擁有了什麼。我有兩個主要的觀點組。一個叫做MapView,它是一個包含可以縮放,平移等位圖的視圖。另一個稱爲StepInfoView,它是一個包含靜態數據的視圖,例如座標數組和關於這些座標的信息。這個視圖也是放大並且以與MapView相同的方式移動,但是,放大的比例因子和數量需要獨立於MapView。Java繼承:抽象類中的「Casting」變量爲靜態
StepInfoView擴展了幾個不同的類(總共6個),所有這些類都需要同步(座標繪製在一個座標之間的線被繪製在另一個上,等等)。
所以,這裏是我的代碼的要點,目前:
public class MapView extends View
{
protected float scale = 1;
protected class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener
{
@Override
public boolean onScale(ScaleGestureDetector detector)
{
scale *= detector.getScaleFactor());
return true;
}
}
}
...
public class StepInfoView extends View
{
static protected float scale = 1;
protected class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener
{
@Override
public boolean onScale(ScaleGestureDetector detector)
{
scale *= detector.getScaleFactor());
return true;
}
}
}
...
public class StepView extends StepInfoView
{
// Custom onDraw, same scale as PathView
}
public class PathView extends StepInfoView
{
// Custom onDraw, same scale as StepView
}
正如你看到的,onScales是相同。我想創建一個抽象類來保存縮放功能,讓我們稱之爲RootView。 MapView和StepInfoView都具有比例尺,但是我無法在RootView中進行比例縮放,因爲MapView比例尺必須獨立於StepInfoView。這裏是我知道將工作的解決方案,但我不喜歡getter和setter的混亂:
abstract class RootView extends View
{
abstract protected float getScale();
abstract protected void setScale(float s);
protected class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener
{
@Override
public boolean onScale(ScaleGestureDetector detector)
{
setScale(getScale() * detector.getScaleFactor());
return true;
}
}
}
...
public class MapView extends RootView
{
public float scale = 1;
protected float getScale(){
return scale;
}
protected void setScale(float s){
scale = s;
}
}
public class StepInfoView extends RootView
{
public static float scale = 1;
protected float getScale(){
return scale;
}
protected void setScale(float s){
scale = s;
}
}
public class StepView extends StepInfoView
{
// Custom onDraw, same scale as PathView
}
public class PathView extends StepInfoView
{
// Custom onDraw, same scale as StepView
}
這工作正是我想要的工作,但再次,有重複相同的代碼( getter和setter以及MapView和StepInfoView中的「scale」變量)。
我希望我能做的是在RootView中聲明一個非靜態的縮放,並在StepInfoView中將它「靜態」轉換爲靜態。這不可能...
你能幫我嗎?
我需要在StepInfoView中保持靜態。如果我在RootView中將其設爲靜態,那麼StepInfoViews和MapViews將不會相互獨立地進行縮放。 – androidnotgenius 2012-08-03 11:37:54
「爲stepinfo scale值創建一些對象容器,並通過StepInfoView的」 「對不起,但我不明白你的建議。 – androidnotgenius 2012-08-03 11:42:15