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

问题描述 投票:0回答:1

我有一个带有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?先谢谢你。

java android imageview
1个回答
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;
    }
});

我没有测试过,但应该能用。

© www.soinside.com 2019 - 2024. All rights reserved.