Android - 在 api 8 中使用 view.setX() 和 setY [英] Android - Use of view.setX() and setY in api 8

查看:27
本文介绍了Android - 在 api 8 中使用 view.setX() 和 setY的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发 android api8.我想在屏幕上动态定位/放置视图.但是要使用 setX 和 setY 我们需要 API 级别 11 及以上.我们如何在 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

推荐答案

您可以使用 LayoutParams 来做到这一点.这些可以添加到android界面的组件中以设置它们的边界和位置.

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

一个例子(在一个RelativeLayout的子视图上设置LayoutParams)

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

请注意,LayoutParams 的类型必须与您要添加它们的子视图的父视图相同.(LinearLayout.LayoutParams 用于 LinearLayoutRelativeLayout.LayoutParams 用于 RelativeLayout 等.

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

此外,除了 childView.setLayoutParams(params); 你还可以使用 parentView.addView(childView,params); 在添加项目时设置 Layoutparams到父容器.

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.

注意!坐标值以像素为单位.由于使用 DP 值来定义界面尺寸是最佳实践,因此您可以使用这段代码将 dp 转换为像素:

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

这篇关于Android - 在 api 8 中使用 view.setX() 和 setY的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆