如何在手指触摸时创建 ImageView?

How to create an ImageView on finger touch?

我有一个带有 RelativeLayout 和现有 ImageView 的 activity。我想要做的是让用户在他触摸屏幕的地方创建一张小图片。我想创建图像的过程应该是这样的:

ImageView imageView = new ImageView(this);
imageView.setImageResource(R.drawable.something);

RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.RelativeLayout01);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
 );
layoutParams.addRule(RelativeLayout.BELOW, R.id.ButtonRecalculate);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

relativeLayout.addView(imageView, layoutParams);

以及获取坐标的过程——就像这样:

@Override
public boolean onTouchEvent(MotionEvent event)
{
int x = (int)event.getX();
int y = (int)event.getY();

switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:
    case MotionEvent.ACTION_MOVE:
    case MotionEvent.ACTION_UP:
}

return true;
}

但是如何将它们结合起来呢?如何将这些坐标设置为新的 ImageView?提前谢谢你。

试试看:

final RelativeLayout rr = (RelativeLayout) findViewById(R.id.rr);
rr.setOnTouchListener(new OnTouchListener() {

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            int x = (int) event.getX();
            int y = (int) event.getY();
            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.WRAP_CONTENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT);
            ImageView iv = new ImageView(getApplicationContext());
            lp.setMargins(x, y, 0, 0);
            iv.setLayoutParams(lp);
            iv.setImageDrawable(getResources().getDrawable(
                    R.drawable.gr1));
            ((ViewGroup) v).addView(iv);
        }
        return false;
    }
});

我没有测试过,但应该可以。