0

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

我试过以下,但没有任何效果。・创建后,使用 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);
4

2 回答 2

5

最后我找到了重点:

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

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

于 2012-06-15T02:10:24.490 回答
2

你可以使用 MarginLayoutParams

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

动态设置边距。

于 2012-05-08T04:09:03.897 回答