【问题标题】:Android. How to move the imageview(set position/margin) when it is created安卓。创建时如何移动图像视图(设置位置/边距)
【发布时间】:2012-05-08 02:24:50
【问题描述】:

我想在应用程序启动时将一些图像放在一个区域中。 由于图像的数量不是固定的,所以我必须动态创建图像。 我想在创建每个图像时设置它们的位置/边距以实现良好的平衡。

我试过following,但没有任何效果。 ・创建后,使用 imageview.layout()。 ・使用 LayoutParams.margins()。 ・使用 AsyncTask 设置边距。 ・activity.runOnUiThread().

这是代码:

    // After access server, if needed then add a imageview to the 'c_box'
    // c_box: the parent that imageview to add.
    FrameLayout c_box = (FrameLayout) findViewById(R.id.c_box);

    MarginLayoutParams mlp = new MarginLayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

    ImageView img1 = new ImageView(this);
    img1.setImageResource(R.drawable.c_file);
    img1.setLayoutParams(params);
    img1.setLongClickable(true);
    img1.setId(img_id);
    c_box.addView(img1);

    img1.setOnTouchListener(listener);


    **// it's possible to set the position by layout or margin?
    img1.layout(100, 100, 200, 200);**

我不知道在哪里调用 invalidate() 方法。


// After access server, if needed then add a imageview to the 'c_box'
    // c_box: the parent that imageview to add.
    FrameLayout c_box = (FrameLayout) findViewById(R.id.c_box);

    MarginLayoutParams mlp = new MarginLayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    mlp.setMargins(100, 100, 200, 200);
    ImageView img1 = new ImageView(this);
    img1.setImageResource(R.drawable.c_file);
    img1.setLayoutParams(mlp);
    img1.setLongClickable(true);
    img1.setId(img_id);
    c_box.addView(img1);

    img1.setOnTouchListener(listener);

【问题讨论】:

    标签: android position imageview oncreate


    【解决方案1】:

    终于找到重点了:

    FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
            LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
            Gravity.NO_GRAVITY);
    

    我错过的第三个参数(Gravity.NO_GRAVITY)。使用它,您可以将视图放置在任何设置宽度/高度的位置。

    【讨论】:

      【解决方案2】:

      你可以使用 MarginLayoutParams

      MarginLayoutParams mlp = (MarginLayoutParams) yourImageViewHere.getLayoutParams();
      mlp.setMargins(leftMargin, topMargin, rightMargin, bottomMargin);//all in pixels
      yourImageViewHere.setLayoutParams(mlp);
      

      动态设置边距。

      【讨论】:

      • 非常感谢。可以在创建imageview并添加到父视图后吗?
      • 好吧,如果您在调用 onDraw 后设置这些边距,我认为您必须重新绘制布局。要强制重绘您的视图,您可以说 yourImageViewHere.invalidate();请参阅developer.android.com/reference/android/view/…。如果这对您有用,请接受我的回答。
      • 非常感谢。如果这个问题得到解决,我很高兴接受你的回答。我编辑了我的问题,添加了一些代码。有什么建议吗?
      • 这在你的 onCreate 方法中吗?您只需要使用 MarginLayoutParams。所以它将是 MarginLayoutParams mlp = (MarginLayoutParams) img1.getLayoutParams(); mlp.setMargins(20, 40, 20, 40); img1.setLayoutParams(mlp);
      • 是的,这是在我的 onCreate 方法中。我已经尝试过 MarginLayoutParams 但没有任何改变。查看我编辑的问题。
      猜你喜欢
      • 2011-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-28
      • 1970-01-01
      • 2016-04-03
      • 1970-01-01
      • 2013-09-02
      相关资源
      最近更新 更多