我有一个空的框架布局,当用户在某个区域点击屏幕时,我想将图像准确放置在他按下的位置。到目前为止,我已经能够获得印刷机的坐标,但是我还不能完全创建新图像(简单的.png红色圆圈)并将其放置在用户点击位置的框架布局中。
这是到目前为止的代码,'ultimoToque []'保留了帧布局内水龙头的X和Y值。
private boolean editMode = true;
private float[] ultimoToque = new float[2];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_graph_maker);
View myView = findViewById(R.id.graph_space);
myView.setOnTouchListener(touchListener);
// IF editMode is true AND last tap is inside frame layout
// THEN place red circle at position defined by ultimoToque[]
}
View.OnTouchListener touchListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
ultimoToque[0] = event.getX();
ultimoToque[1] = event.getY();
}
double x = ultimoToque[0];
double y = ultimoToque[1];
Log.i("TAG", "Novas coordenadas x: " + x + ", y: " + y);
return false;
}
};
答案 0 :(得分:0)
不清楚是要在每个水龙头上放置新图像还是要将同一图像移到新位置。
放置新图像
将myView
设置为全局
private boolean editMode = true;
private float[] ultimoToque = new float[2];
private RelativeLayout myView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_graph_maker);
myView = findViewById(R.id.graph_space);
myView.setOnTouchListener(touchListener);
}
使用此功能添加新图像
private void addNewImage(double X, double Y) {
ImageView img = new ImageView(this);
img.setImageResource(R.drawable.yourimage);
myView.addView(img);
RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams) img.getLayoutParams();
lParams.leftMargin = (int)X;
lParams.topMargin = (int)Y;
img.setLayoutParams(lParams);
}
像这样调用此函数
View.OnTouchListener touchListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
ultimoToque[0] = event.getX();
ultimoToque[1] = event.getY();
}
double x = ultimoToque[0];
double y = ultimoToque[1];
addNewImage(x, y)
Log.i("TAG", "Novas coordenadas x: " + x + ", y: " + y);
return false;
}
};
要将同一图像移动到新位置,只需将新图像全局设置并更改其leftMargin
和topMargin
值即可。
如果您要以触摸坐标为中心设置圆,只需将图像宽度和高度的一半递减到顶部和左侧的值即可。