Android. How to move the imageview(set position/margin) when it is created

假如想象 提交于 2019-12-12 03:08:29

问题


I want to put some images in an area at the application start. As the number of images is not a fixed amount, so I have to create images dynamically. I want to set the position/margin of every images while they're created for good balance.

I have tried follows, but there is no efficacy. ・After Created, use imageview.layout(). ・Use LayoutParams.margins(). ・Use AsyncTask to set margins. ・activity.runOnUiThread().

This is the code:

    // 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);**

I don't know where to call the invalidate() method.


// 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);

回答1:


Finally I found the point:

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

the 3rd param(Gravity.NO_GRAVITY) that I missed. use it you can position views at anywhere with setting width/height.




回答2:


You could use MarginLayoutParams

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

To set your margins dynamically.



来源:https://stackoverflow.com/questions/10491736/android-how-to-move-the-imageviewset-position-margin-when-it-is-created

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!