Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
440 views
in Technique[技术] by (71.8m points)

Android - Use of view.setX() and setY in api 8

i am working on android api8. i want to position/place a view on screen dynamically. but to use setX and setY we need API level 11 and above. how can we use it in API 8 or is there any alternative for this? need help

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do this by using the LayoutParams. These can be added to components of the android interface to set their bounds and position.

An example (setting the LayoutParams on a child view of a RelativeLayout)

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); //The WRAP_CONTENT parameters can be replaced by an absolute width and height or the FILL_PARENT option)
params.leftMargin = 50; //Your X coordinate
params.topMargin = 60; //Your Y coordinate
childView.setLayoutParams(params);

Take note that the type of the LayoutParams must be equal to the parent of the childview you want to add them to. (LinearLayout.LayoutParams for a LinearLayout , RelativeLayout.LayoutParams for a RelativeLayout etc.).

Also, instead of childView.setLayoutParams(params); you can also use parentView.addView(childView,params); to set the Layoutparams when the item is added to the parent container.

NOTE! The values for the coordinates are in pixels. Since it's best practice to use DP values to define your interface sizes you could use this piece of code to convert dp to pixels:

private int getPixels(int dipValue){ 
     Resources r = getResources();
     int px = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dipValue,   r.getDisplayMetrics());
     return px; 
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...