本文介绍了将它们添加到活动后,视图getX()和getY()返回0.0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我实例化了一个新的View并通过layout.addView将其添加到活动中.如果我对该视图尝试使用getX()或getY(),我总会得到0.0.
in ManActivity onCreate() I instantiated a new View and added it via layout.addView to the activity. If i try getX() or getY() for that view I always get 0.0.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout main = (RelativeLayout)findViewById(R.id.main);
RelativeLayout.LayoutParams squarePosition = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
GameToken square1 = new GameToken(this,GameToken.SQUARE, fieldHeight,fieldWidth);
squarePosition.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
squarePosition.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
main.addView(square1, squarePosition);
System.out.println(square1.getX()); //Prints '0.0'
System.out.println(square1.getY()); //Prints '0.0'
推荐答案
ViewGroup
(例如RelativeLayout
)不会立即布置其子级,因此您的View尚不知道其在屏幕上的位置.您需要等待RelativeLayout
完成布局遍历,然后才能进行.
ViewGroup
s such as RelativeLayout
do not layout their children immediately, and thus your View does not yet know where it will lie on screen. You need to wait for the RelativeLayout
to complete a layout pass before that can happen.
您可以像这样监听全局布局事件:
You can listen for global layout events like so:
view.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// Layout has happened here.
// Don't forget to remove your listener when you are done with it.
view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
});
这篇关于将它们添加到活动后,视图getX()和getY()返回0.0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!