如何删除我创建的视图?

时间:2016-05-18 08:50:28

标签: android

enter image description here美好的一天!我已经使用了这一行" ImageView iv = new ImageView(this)"在java中创建一个imageview但是在创建之后我想用一个按钮删除它,我该怎么做?

我的目标是当我触摸屏幕时,图像将跟随触摸的事件。

这是我的代码:

 public boolean onTouchEvent(MotionEvent event) {

    float pointX = event.getX();
    float pointY = event.getY();
     x = (int) event.getX();
     y = (int) event.getY();

    RelativeLayout re = (RelativeLayout)((Activity)context).findViewById(R.id.re);
    ImageView iv = new ImageView(this.context);
    iv.setImageResource(R.drawable.aw);
    ImageView iv2 = new ImageView(this.context);
    iv2.setImageResource(R.drawable.aw);
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(80,80);
    params.topMargin=y;
    params.leftMargin=x;

    // Checks for the event that occurs
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            path.moveTo(pointX, pointY);
            if(flag ==0) {
                re.removeView(iv2);
                re.addView(iv, params);
                flag = 1;
            }
            if(flag == 1)
            {
                re.removeView(iv);
                re.addView(iv2, params);
                flag = 0;
            }
            if(c==1) {
                Context wdd = getContext();
                Intent i = new Intent(wdd, MainActivity.class);
                wdd.startActivity(i);
            }
            return true;
        case MotionEvent.ACTION_MOVE:
            if(flag ==0) {
                re.removeView(iv2);
                re.addView(iv, params);
                flag = 1;
            }
            if(flag == 1)
            {
                re.removeView(iv);
                re.addView(iv2, params);
                flag = 0;
            }
            path.lineTo(pointX, pointY);
break;
 postInvalidate();
return true;
}

2 个答案:

答案 0 :(得分:1)

如果您的意思是隐藏 ImageView,请根据具体情况删除,请执行以下操作:

if (your_condition) {
your_image_view.setVisibility(View.GONE);
 } else {
your_image_view.setVisibility(View.VISISBLE);
}

如果您需要删除当前设置为 ImageView 的图像,请在上面的 if ... else 中执行此操作(根据条件)

your_image_view.setImageResource(android.R.color.transparent); 

OR

your_image_view.setImageBitmap(null);

如果您需要完全删除 ImageView ,请在ImageView的容器中的 if .... else 中调用它:

container.removeView(your_image_view);

答案 1 :(得分:0)

将ImageView的父布局(RelativeLayout,LinearLayout或其他任何内容)设置为ViewGroup。然后从该ViewGroup中删除该ImageView。尝试这样的事情:

ViewGroup container = (ViewGroup) findViewById(R.id.parent_of_your_image_view);
View yourImg = (View) findViewById(R.id.your_image_view);
container.removeView(yourImg);