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

时间:2020-06-08 17:39:31

标签: java android imageview

我有一个带有RelativeLayout的活动,并且其中已有一个ImageView。我想做的是允许用户在他触摸屏幕的地方创建一张小图片。我想创建图像的过程应该是这样的:

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?预先谢谢你。

1 个答案:

答案 0 :(得分:0)

尝试:

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;
    }
});

我没有测试它,但是它应该可以工作。

相关问题