3

我想设置 Imageview 的边距。我想要实现的是将一张图像移动到一定距离。屏幕的内容是RelativeLayout,左边有ImageView,右边有button。现在我想在单击 100 次按钮时在图像和按钮之间的间隙内从左到右移动图像。我遵循的代码如下:

private static int count= 1 ;

public void onClick(View view) {


    RelativeLayout lay = (RelativeLayout)findViewById(R.id.layout1);
    ImageView i1= (ImageView)findViewById(R.id.img1);
    ImageButton btn= (ImageButton)findViewById(R.id.iBtn);

    int i1Width = i1.getWidth();
    int btnWidth = btn.getWidth();
    int totalMragine = lay.getWidth() - i1Width - btnWidth ; //the total margine image will move.
    int stepSize =  (lay.getWidth() - i1Width - btnWidth ) / 100;   
    int step = stepSize * count++;  

    Log.i("i1Width ", ""+i1Width );
    Log.i("btnWidth ", ""+btnWidth );
    Log.i("lay.getWidth()", ""+lay.getWidth());     
    Log.i("stepSize", ""+stepSize);     
    Log.i("count", ""+count);

    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    lp.setMargins(step, 0, 0, 0);
    i1.setLayoutParams(lp);     

    LinearLayout.LayoutParams lp1 = (LinearLayout.LayoutParams) horse.getLayoutParams();
    Log.i("currentMargine", ""+lp1.leftMargin);

    if(lp1.leftMargin >= totalMragine ){
        Log.i("Result", "maringe over");
    }
}

我想知道我设置的边距是整数,但步长的值是浮点数。那么如何在 LayoutParams 中设置边距浮动?还是有其他方法可以做到这一点?

4

1 回答 1

0

你可以做一件事计算每次移动的距离,就像移动的时候一样

移动距离 = 剩余长度/剩余点击次数

在最后一步(第 100 步)中,它将以错误 < 结束5 像素和. 5px 太小了)

1st click  distance_to_move = 370/100;   as round off come 4 

2nd click  distance_to_move = 366/99;    as round off come 4 

3rd click  distance_to_move = 362/98;    as round off come 4 

所以 movemnt 将在 px 44444...3444...3444..3444...

于 2012-06-22T06:02:56.320 回答