Android系统.如何在创建时移动imageview(设置位置/边距)

kin*_*mei 0 android position imageview oncreate

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

我试过以下,但没有效果.·创建后,使用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);**
Run Code Online (Sandbox Code Playgroud)

我不知道在哪里调用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);
Run Code Online (Sandbox Code Playgroud)

kin*_*mei 5

最后我发现了一点:

FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
        LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
        Gravity.NO_GRAVITY);
Run Code Online (Sandbox Code Playgroud)

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