更改一个对象的值会影响其他

时间:2016-02-17 10:13:08

标签: android relativelayout

我面临一个奇怪的问题。

我有一个班级:

public class HeatMap {
    public View view;
    public RelativeLayout.LayoutParams orignalParam;
    public RelativeLayout.LayoutParams centerParam;
    public int originalPos[]=new int[2];
    public boolean Position;
    public float Positions[]=new float[2];
    public int centerPos[]=new int[2];
    public HeatMap(View view){
        this.view=view;
        this.Position=false;
        orignalParam= (RelativeLayout.LayoutParams) view.getLayoutParams();
        centerParam =
                (RelativeLayout.LayoutParams) view.getLayoutParams();

    }

在另一个班级我正在做以下事情

    static HeatMap staticView;

  public static void TranslateViewAtCenter1(Context context, int pop){

        HeatMap hMap=Constants.heatMapList.get(pop);



 staticView=hMap;

      //  staticView.centerParam.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.CENTER_VERTICAL);
       // staticView.view.setLayoutParams(hMap.centerParam);
        View rootChild = hMap.view;
        int originalPos[] = new int[2];
        rootChild.getLocationOnScreen(originalPos);

        int mainViewWidth=HomeScreenActivity.rl_heatmap_view.getMeasuredWidth();
        int mainViewHeight=HomeScreenActivity.rl_heatmap_view.getMeasuredHeight();

        RelativeLayout.LayoutParams lp= (RelativeLayout.LayoutParams)rootChild.getLayoutParams();

        int left=lp.leftMargin;
        int top=lp.topMargin;


        Log.e("ORGPOs_center", hMap.originalPos[0] + " , " + hMap.originalPos[1] + " ," + hMap.view.getId());
        Log.e("XXWidhtHeight",rootChild.getMeasuredWidth()+" , "+rootChild.getMeasuredHeight());


        int xDest = mainViewWidth/2;
        xDest -= (rootChild.getMeasuredWidth()/2);
        int yDest = mainViewHeight/2 - (rootChild.getMeasuredHeight()/2)/*-statusBarOffset*/;
        int xD= CommonMethods.pxToDp(xDest-left,context);
        int yD= CommonMethods.pxToDp(yDest - top, context);
        hMap.centerPos[0]=xD;
        hMap.centerPos[1]=yD;


        TranslateIntoCenter intoCenter=new TranslateIntoCenter();
        intoCenter.setView(hMap);


        TranslateAnimation anim = new TranslateAnimation( xD, 0 , yD, 0 );
        anim.setAnimationListener(intoCenter);
        anim.setDuration(500);
        anim.setFillAfter(true);
        hMap.view.startAnimation(anim);
    }

问题在于这两行

staticView.centerParam.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.CENTER_VERTICAL);
       staticView.view.setLayoutParams(hMap.centerParam);

如果我对这些行进行评论,那么每件事情都适用于hMap,但在更改staticView属性时,hMap也会发生变化。我已经检查了整个代码,我没有使用staticView或者在staticView任何其他地方做任何事情。

感谢。

1 个答案:

答案 0 :(得分:1)

添加行

staticView=hMap;

您正在获取对hMap对象的引用。您没有创建新对象。这意味着staticView和hMap都指向同一个对象,如果你在其中任何一个中进行更改,它们都会反映在staticView和hMap中。

你必须创建一个新的HeatMap对象