Android setX() and setY() behaving weird(Android setX() 和 setY() 行为怪异)
问题描述
I am trying to dynamically create and then move an image in an Android activity. However, the setX() and setY() methods seem to not work correctly. It correctly sets the position of an image when it is first created and placed, but any attempt to update it results in the image being placed in the wrong spot. For instance, the image moves on the following code:
ImageView image;
RelativeLayout layout = (RelativeLayout)findViewById(R.id.activity_this);
if(action == MotionEvent.ACTION_DOWN){
image = new ImageView(MyClass.this);
layout.addView(image, width, height);
image.setX(206);
image.setY(206);
}
else if(action == MotionEvent.ACTION_MOVE){
if(image != null){
image.setX(206);
image.setY(206);
}
}
On ACTION_MOVE the image is moved even though the x and y position values remain the same. The parent of the image remains the same. The size remains the same. If I get the x and y values it will still say 206, but it is not placed at (206, 206) on the activity anymore. I am lost as to why this is happening. I can't find any indication that the image has been altered except for it physically changing location.
Really, this shouldn't be happening. Alternatively, try setting another variable and setting x and y to it, or get x and get y and add a 0 to each one of them for same location.
As stated in Android - Use of view.setX() and setY in api 8, if you have searched, there is another solution that also works even before api 8.
LayoutParams
works like this -
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); //WRAP_CONTENT param can be FILL_PARENT
params.leftMargin = 206; //XCOORD
params.topMargin = 206; //YCOORD
childView.setLayoutParams(params);
There is more information there. I hope this helps
这篇关于Android setX() 和 setY() 行为怪异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Android setX() 和 setY() 行为怪异
基础教程推荐
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01