如何在安卓系统中清除视图?

5

我已经在Android上创建了一个简单的绘图演示应用程序,现在有人能告诉我如何在一次点击中删除视图并清除屏幕吗?我已经尝试过以下方法,请帮助我完成它...提前感谢!

main.java

package com.example.singletouch;

import com.example.singletouch.R.attr;

import android.os.Bundle;
import android.app.Activity;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class MainActivity extends Activity {
    ImageView pen;
     SingleTouchView mDrawView;

     ImageView remove;
    LinearLayout pens;

    LinearLayout pen1, pen2, pen3, pen4;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         mDrawView = (SingleTouchView) findViewById(R.id.myview);


        pen = (ImageView) findViewById(R.id.pen);
        pens = (LinearLayout) findViewById(R.id.linear);
        pens.setVisibility(View.GONE);
        pen1 = (LinearLayout) findViewById(R.id.pen1);
        pen2 = (LinearLayout) findViewById(R.id.pen2);
        pen3 = (LinearLayout) findViewById(R.id.pen3);
        pen4 = (LinearLayout) findViewById(R.id.pen4);
    remove=(ImageView)findViewById(R.id.remove);
        /*
         * pen1.setOnClickListener(this); pen2.setOnClickListener(this);
         * pen3.setOnClickListener(this); pen4.setOnClickListener(this);
         */

        pen.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                pens.setVisibility(View.VISIBLE);



            }
        });pens.setVisibility(View.GONE);
        pen1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                 mDrawView.setPen(SingleTouchView.DrawingPens.PEN_1);
                pens.setVisibility(View.GONE);


            }
        });
        pen2.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                 mDrawView.setPen(SingleTouchView.DrawingPens.PEN_2);
                pens.setVisibility(View.GONE);

            }
        });
        pen3.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                pens.setVisibility(View.GONE);
                 mDrawView.setPen(SingleTouchView.DrawingPens.PEN_3);

            }
        });
        pen4.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                pens.setVisibility(View.GONE);
                 mDrawView.setPen(SingleTouchView.DrawingPens.PEN_4);


            }
        });
        remove.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {


            }
        });


    }

}

SingleTouchView.java

    package com.example.singletouch;

    import java.util.AbstractMap;
    import java.util.Map;
    import java.util.concurrent.ConcurrentLinkedQueue;

    import android.R.color;
    import android.content.Context;
import android.graphics.Bitmap;
    import android.graphics.Canvas;
    import android.graphics.Color;
    import android.graphics.Paint;
    import android.graphics.Path;
import android.graphics.PorterDuff.Mode;
    import android.util.AttributeSet;
    import android.view.MotionEvent;
    import android.view.View;
    import android.widget.ImageView;
import android.widget.Switch;

     public class SingleTouchView extends View{
         public int width;
         public  int height;
            public Bitmap  mBitmap;
            public Canvas  mCanvas;
            public Path    mPath;
            public Paint   mBitmapPaint;
            Context context;

            public Paint circlePaint;
            public Path circlePath;

         public enum DrawingPens {
                PEN_1(6),
                PEN_2(4),
                PEN_3(2),
                PEN_4(1);

                final public Paint mPaint;

                /**
                 * Constructor
                 *
                 * @param width width of stroke
                 * @param color color of stroke
                 */
                private DrawingPens(final int width) {
                    mPaint = new Paint();

                    mPaint.setAntiAlias(true);
                    mPaint.setStrokeWidth(width);
                    //mPaint.setColor(color);
                    mPaint.setStyle(Paint.Style.STROKE);
                    mPaint.setStrokeJoin(Paint.Join.ROUND);
                }


                /**
                 * @return corresponding paint
                 */
                Paint getPaint() {
                    return mPaint;
                }
            }




            public SingleTouchView(final Context context) {
                super(context);

                init(context);
            }

            public SingleTouchView(final Context context, final AttributeSet attrs) {
                super(context, attrs);

                init(context);
            }

            public SingleTouchView(final Context context, final AttributeSet attrs, final int defStyle) {
                super(context, attrs, defStyle);

                init(context);
            }

            /** To store Paint - Path relation */
            // TODO: depending on exact limits, more optimal ways can be found
            private ConcurrentLinkedQueue<Map.Entry<Path, DrawingPens>> mPaths = new ConcurrentLinkedQueue<Map.Entry<Path, DrawingPens>>();

            /** Cached current path, <b>NOTE:</b> this field is tail at mPaths and is used it only for caching, not drawing */
            private Path mCurrentPath;

            /**
             * Inits internal views data, should be called from every constructor
             *
             * @param context {@link Context}
             */
            private void init(final Context context) {
                /* TODO: if some values of paints cannot be determined in static context (in enum),
                   then Paints should be created here and used via EnumMap */

                // Initial pen
                setPen(DrawingPens.PEN_1);

            }



            @Override
            public void onDraw(Canvas canvas){
                // just to draw background
                super.onDraw(canvas);

                // Draw all paths
                for (Map.Entry<Path, DrawingPens> entry : mPaths) {
                    canvas.drawPath(entry.getKey(), entry.getValue().getPaint());
                }
            }

            @Override
            public boolean onTouchEvent(MotionEvent me){
                float eventX = me.getX();
                float eventY = me.getY();

                switch (me.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        mCurrentPath.moveTo(eventX, eventY);
                        return true;
                    case MotionEvent.ACTION_MOVE:
                        mCurrentPath.lineTo(eventX, eventY);
                        break;
                    case MotionEvent.ACTION_UP:
                        break;
                }

                invalidate();

                return true;
            }

            /**
             * Setter for new pen
             *
             * @param pen {@link DrawingPens} to be used for next drawing
             */
            public void setPen(final DrawingPens pen) {
                // put latest item to the queue
                mCurrentPath = new Path();
                mPaths.add(new AbstractMap.SimpleImmutableEntry<Path, DrawingPens>(mCurrentPath, pen));
            }
           public void clear(View v){

           }

        }

main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    tools:context=".MainActivity" >

    <com.example.singletouch.SingleTouchView
        android:id="@+id/myview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_above="@+id/pen" />

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="@drawable/menubar"
        android:padding="2dp"
        android:weightSum="4" >

        <ImageView
            android:id="@+id/pen"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_alignParentBottom="true"
            android:layout_weight="1"
            android:gravity="center"
            android:src="@drawable/pen" />

        <ImageView
            android:id="@+id/eraser"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_alignParentBottom="true"
            android:layout_weight="1"
            android:src="@drawable/eraser" />

        <ImageView
            android:id="@+id/color"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_alignParentBottom="true"
            android:layout_weight="1"
            android:src="@drawable/color" />

        <ImageView
            android:id="@+id/remove"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_alignParentBottom="true"
            android:layout_weight="1"
            android:src="@drawable/remove" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/linear"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/linearLayout1"
        android:layout_alignParentLeft="true"
        android:background="#eeeeee"
        android:orientation="horizontal"
        android:visibility="gone"
        android:weightSum="4" >

        <LinearLayout
            android:id="@+id/pen1"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:gravity="center" >

            <ImageView
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:src="@drawable/pen1" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/pen2"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:gravity="center" >

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:src="@drawable/pen2" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/pen3"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:gravity="center" >

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:src="@drawable/pen3" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/pen4"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:gravity="center" >

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:src="@drawable/pen4" />
        </LinearLayout>
    </LinearLayout>

</RelativeLayout>

我不确定你的意思,但也许这个链接可以帮到你:https://dev59.com/kF3Ua4cB1Zd3GeqP_2Bq - user2617212
@yser2617212-m 发布我的 XML 文件,以便您了解情况...!我想通过一次点击清除我绘制的所有路径...! - jigar
亲爱的jigar,如果你想清除绘制的路径,你可以通过设置画布的颜色来清除它。你不需要移除视图。为了清除mPaths的内容,只需将其分配为@null。垃圾回收器会清理内存。我建议仅在布局中具有可变数量的相同类型视图时添加或删除视图,例如,如果你有多个画布并且想要删除其中一个。 - Trinimon
@Trinimon,你能放一些代码吗...兄弟..! - jigar
4个回答

5

Jus use ...

mCanvas.drawColor(Color.BLACK);

用于清除画布或设置背景色的代码。例如:

remove.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        // clear canvas contents  
        mCanvas.drawColor(Color.BLACK);

        // create new path list; old one will be garbage collected 
        ConcurrentLinkedQueue<Map.Entry<Path, DrawingPens>> mPaths = 
                  new ConcurrentLinkedQueue<Map.Entry<Path, DrawingPens>>();

        pens.setVisibility(View.VISIBLE);
    }

备注:如果需要从容器动态地移除视图,请使用removeView(....)方法。例如:

((ViewGroup)viewToRemove.getParent()).removeView(viewToRemove);

希望这能帮助到您...干杯!

@Trinimon-Brother...我成功地通过layout.removeAllViews()清除了屏幕,但是...之后我无法再用笔绘制...!:( - jigar
亲爱的 jigar,如果您删除视图,则意味着包含画布的底层对象将被删除。因此,如果您想继续绘制,必须首先动态创建一个新画布。但是,如果您始终只有一个画布,我认为您不需要删除它。只需通过清除画布内容来清除绘制的路径、线条、弧等。使用 drawColor(...) 来实现。 - Trinimon
请查看上面添加的onClick()方法 :) - Trinimon
我之前选错了(pen) - 实际上是想要 remove ;) 将 drawColor(...) 放在你的 remove 按钮的 onClick(...) 监听器中。 - Trinimon

4
remove.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                layout.removeView(mDrawView);
                mDrawView = new SingleTouchView(MainActivity.this);
                layout.addView(mDrawView);
            }
        });

看起来是一个有效的选项 :) ... 就像我说的一样:如果你删除画布(视图),你需要创建一个新的画布(视图)... :) - Trinimon

1
将您想要清除的屏幕部分放在单个xml布局中,例如:
<RelativeLayout
android:id="@+id/layout"
android:layout_width="wrap_content"
android:layout_height= "wrap_content">

    The Views that have to be gone on click

</RelativeLayout>

然后在按钮的 onClick() 中的代码中给出。
((RelativeLayout) findViewById(R.id.layout)).setVisiblity(View.GONE));

编辑:

如果您想清除 ImageView,请使用:

((ImageView) findViewById(R.id.imageView)).setImageDrawable(null);

这只是让视图消失的操作 :) - Trinimon
这不是一个好的做法.....!!!我想永远澄清它....!!!那就不会再出现了...! - jigar
我有点困惑你在寻找什么。起初我以为你想清除(绘图)画布,但似乎不是这样。现在看起来,你似乎是想要类似于https://dev59.com/tm865IYBdhLWcg3wceRU中描述的内容(即从父布局中删除视图)。老实说:我认为这不是一个好主意,但也许会有所帮助;) - Trinimon
@jigar 那么你确切想要什么?你想让视图再次出现吗?如果是这样,每当您希望发生这种情况时,可以将可见性设置为VISIBLE。 - user2041902
@jigar 这是一个imageView,你可以将其中的图片设置为 null。 - user2041902
显示剩余4条评论

0

你可以绘制透明颜色而不是实心颜色,这样可以帮助你在将其用作画布背景时不会覆盖其他视图。

mCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);

我从这个答案中得到了这个方法:https://dev59.com/kG025IYBdhLWcg3w6KSO#10882301


2
这不是一个完整的答案。请始终描述您正在做什么,并针对具有许多其他答案的问题,告诉我们为什么实际上需要您的答案/它在哪些方面不同。请编辑它。 - finnmglas
@finnmglas 接受的答案详细说明了它可能在哪里使用,但这是相关代码的另一种选择。 它之所以不同,是因为它使用透明度,而不是黑色。 当前的答案已经很明显了所有这些。 请尽量不要因为您选择不投入任何努力而阻止有用的信息。 - Abandoned Cart

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接