【问题标题】:Set layout margine with float value in android在android中使用浮点值设置布局边距
【发布时间】:2012-06-22 05:49:29
【问题描述】:

我想设置 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 中设置边距浮动?还是有其他方法可以做到这一点?

【问题讨论】:

  • 小数点后的值重要吗?把它们四舍五入不好吗?
  • 没有。例如,btn 和 img 之间的间隙为 370。因此步长为 370 / 100。这应该是 3.7,但由于它是整数,因此它给出了 3 作为步长。实际上它应该移动的是每步 3.7px。
  • gr8.....现在很有趣.......

标签: java android android-layout mobile


【解决方案1】:

你可以做一件事,计算每次移动的距离

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

在最后一步(第 100 步)中,它会以错误结束 . 5px 和 . 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...

【讨论】:

    猜你喜欢
    • 2013-05-12
    • 1970-01-01
    • 2012-07-28
    • 2017-02-25
    • 1970-01-01
    • 2013-11-23
    • 2013-10-20
    • 2016-02-24
    • 1970-01-01
    相关资源
    最近更新 更多