如何用XML,Java设置图片的坐标

时间:2018-03-16 14:24:44

标签: java xml

您好我正在尝试使用java和XML创建一个应用程序,我希望在页面上的特定位置创建一张图片。我该怎么办?
我试过了:

ImageView sprite = (ImageView)findViewById(R.id.sprite);
sprite.setX(0);
sprite.setY(500);

我在sprite.setX(0);sprite.setY(500);发错了 setX或setY不存在......

1 个答案:

答案 0 :(得分:0)

  

首先,我没有看到与XML有任何关系,你应该发布所有代码,以便我们可以分析它并找出错误产生的内容   很奇怪,你的ImageView控件中没有setX和setY方法,也许你正试图在错误的地方调用setX和setY

但假设不是,您可以尝试以下方法:

AbsoluteLayout.LayoutParams param = new AbsoluteLayout.LayoutParams(int width, int height, int x, int y)

sprite.setLayoutParams(param);

,其中

int X = 0;
int Y = 500;
YourLayout.LayoutParams param = new YourLayout.LayoutParams(sprite.getMeasuredWidth(), sprite.getMeasuredHeight(), X, Y);
sprite.setLayoutParams(param);

另外

假设您希望屏幕上的ImageView大小为80x90,位置为90x60

RelativeLayout relativeLayout = new RelativeLayout(this);

ImageView sprite = (ImageView)findViewById(R.id.sprite);

//Where 80 is the width and 90 the height
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(80, 90);

// Setting position of our ImageView
//you can use the margins of the layout
layoutParams.leftMargin = 80;
layoutParams.topMargin = 90;
//layoutParams.rightMargin = 80; //Example
//layoutParams.bottomMargin = 90; //Example


relativeLayout.addView(imageView, layoutParams);

无论如何,我建议您发布完整的代码,以便我们为您提供帮助