Change View position

痴心易碎 提交于 2019-12-24 05:04:38

问题


My View is not generated programmatically, but it is found with findbyid function. After getting view I like to position it properly.

To do that I am using layout function to change position of view in onCreate with given parameters. Problem is that is not working properly and view stays in top left corner.

Function works fine while using it onTouch after activity is loaded. What I am doing wrong, is there another to set view based on these four parameters that layout uses.

Edit:

Params are loaded from DB. this is what I use in onCreate:

setContentView(R.layout.baseview);

View view=(ImageView) findViewById(R.id.blah);      

int top=cursor.getInt(cursor.getColumnIndex(CallerViewDB.TOP));
int bottom=cursor.getInt(cursor.getColumnIndex(CallerViewDB.BOTTOM));
int left=cursor.getInt(cursor.getColumnIndex(CallerViewDB.LEFT));
int right=cursor.getInt(cursor.getColumnIndex(CallerViewDB.RIGHT));
view.layout(left, top, right, bottom);

Loaded values are right, checked it w sqllite browser. It seems that calling layout function in onCreate does not anything. Is there any alternative?


回答1:


Ok after some reasearch this is how it is done:

RelativeLayout.LayoutParams parms=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
parms.leftMargin=left;
parms.rightMargin=right;
parms.topMargin=top;
parms.bottomMargin=bottom;
view.setLayoutParams(parms);



回答2:


/**
 onPreDraw: Callback method to be invoked when the view tree is about to be
 drawn. At this point, all views in the tree have been measured and given a
 frame. Clients can use this to adjust their scroll bounds or even to request
 a new layout before drawing occurs.
*/

ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();
OnPreDrawListener onPreDrawListener = new OnPreDrawListener()
{
    @Override
    public boolean onPreDraw()
    {
        view.layout(....);
        return true;
    }
};
viewTreeObserver.addOnPreDrawListener(onPreDrawListener);



回答3:


This is a very bad idea in most scenario. Android devices vary in screen size, orientation and resolution. It is recommended that you do not use absolute positioning, and instead using relative positioning.

Read up on RelativeLayout, and I'm sure it will do what you need.



来源:https://stackoverflow.com/questions/7217614/change-view-position

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