Change View position

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?

Answer1:

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

Answer2:

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

Answer3:

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.

人吐槽 人点赞

Recommend

Comment

用户名: 密码:
验证码: 匿名发表

你可以使用这些语言

查看评论:Change View position