草庐IT

Android-Textview 在拖动操作时消失

coder 2023-11-21 原文

我正在创建一个图像编辑应用程序。我在其中提供了打开相机或画廊以选择图片的便利。选择图片后,用户将导航到其他页面。在其他显示图片的页面中,我使用了一个实现了 AppCompactImageView 的 View 。现在,我正在提供使用 edittext 添加文本的便利。单击软键盘的“完成”按钮时,edittext 将消失并被 TextView 取代。现在我想将这个 TextView 拖到整个布局中。但是在 drop 操作之后,它就消失了。下面是我的代码。任何帮助都将不胜感激。

  1. DrawActivity.java

    公共(public)类 DrawActivity 扩展 AppCompatActivity {

    DrawView imgView;
    Button resetBtn, saveBtn;
    ImageButton undoBtn;
    Bundle extras;
    Context context;
    EditText addTxtBox;
    ImageView brushImg, fontImg;
    TextView addedTxtView;
    // LinearLayout mainLinear;
    RelativeLayout mainRelative;
    public int rowX, rowY;
    public String txtVal;
    private android.widget.RelativeLayout.LayoutParams layoutParams;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportActionBar().hide();
        setContentView(R.layout.activity_draw);
    
        context = this.getApplicationContext();
    
        mainRelative = (RelativeLayout) findViewById(R.id.relativeLayout1);
        imgView = (DrawView) findViewById(R.id.frag_home_iv_main);
        resetBtn = (Button) findViewById(R.id.clearBtn);
        undoBtn = (ImageButton) findViewById(R.id.undoBtn);
        saveBtn = (Button) findViewById(R.id.saveBtn);
        addTxtBox = (EditText) findViewById(R.id.addTxt);
        brushImg = (ImageView) findViewById(R.id.imageBrush);
        fontImg = (ImageView) findViewById(R.id.imageFont);
    
        addedTxtView = (TextView) findViewById(R.id.drawTextView);
        addedTxtView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                ClipData.Item item = new ClipData.Item((CharSequence)v.getTag());
                String[] mimeTypes = {ClipDescription.MIMETYPE_TEXT_PLAIN};
    
                ClipData dragData = new ClipData(v.getTag().toString(),mimeTypes, item);
                View.DragShadowBuilder myShadow = new View.DragShadowBuilder(addedTxtView);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    Log.d("Vishal sdk","in if");
                    v.startDragAndDrop(dragData, myShadow, null, 0);
                } else {
                    Log.d("Vishal sdk","in else");
                    v.startDrag(dragData, myShadow, null, 0);
                }
                return false;
            }
        });
    
    
        addedTxtView.setOnDragListener(new View.OnDragListener() {
            @Override
            public boolean onDrag(View v, DragEvent event) {
                Log.d("Vishal check", String.valueOf(event.getAction()));
                switch(event.getAction()) {
                    case DragEvent.ACTION_DRAG_STARTED:
                        layoutParams = (RelativeLayout.LayoutParams)v.getLayoutParams();
                        Log.d("Vishal Drag", "Action is DragEvent.ACTION_DRAG_STARTED");
                        return true;
                        // Do nothing
    
                    case DragEvent.ACTION_DRAG_ENTERED:
                        Log.d("Vishal Drag", "Action is DragEvent.ACTION_DRAG_ENTERED");
                        int x_cord = (int) event.getX();
                        int y_cord = (int) event.getY();
                        return true;
    
                    case DragEvent.ACTION_DRAG_EXITED :
                        Log.d("Vishal Drag", "Action is DragEvent.ACTION_DRAG_EXITED");
                        x_cord = (int) event.getX();
                        y_cord = (int) event.getY();
                        layoutParams.leftMargin = x_cord;
                        layoutParams.topMargin = y_cord;
                        v.setLayoutParams(layoutParams);
                        v.setVisibility(View.VISIBLE);
                        // view.setVisibility(View.VISIBLE);
                        return true;
    
                    case DragEvent.ACTION_DRAG_LOCATION  :
                        Log.d("Vishal Drag", "Action is DragEvent.ACTION_DRAG_LOCATION");
                        x_cord = (int) event.getX();
                        y_cord = (int) event.getY();
                        return true;
    
                    case DragEvent.ACTION_DRAG_ENDED   :
                        Log.d("Vishal Drag", "Action is DragEvent.ACTION_DRAG_ENDED");
                        return true;
                        // Do nothing
    
                    case DragEvent.ACTION_DROP:
                        Log.d("Vishal Drag", "ACTION_DROP event");
                       /* x_cord = (int) event.getX();
                        y_cord = (int) event.getY();
                        View view = (View) event.getLocalState();
                        view.setX(x_cord - (view.getWidth() / 2));
                        view.setY(y_cord - (view.getWidth() / 2));
                        view.setVisibility(View.VISIBLE);*/
    
                        return true;
                        // Do nothing
                    default:
                        return true;
    
                }
                //return true;
            }
        });
    
    
        addTxtBox.setImeOptions(EditorInfo.IME_ACTION_DONE);
        addTxtBox.setRawInputType(InputType.TYPE_CLASS_TEXT);
    
        addTxtBox.setVisibility(View.GONE);
        // addedTxtView.setVisibility(View.GONE);
    
    
        extras = getIntent().getExtras();
        imgView.setImageURI(Uri.parse(extras.getString("selectedImg")));
    
        imgView.setDrawingCacheEnabled(true);
    
        brushImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imgView.setBrushActive(true);
            }
        });
    
        fontImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imgView.setBrushActive(false);
                addTxtBox.setVisibility(View.VISIBLE);
                addTxtBox.requestFocus();
                InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,InputMethodManager.HIDE_IMPLICIT_ONLY);
            }
        });
    
        addTxtBox.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    Toast.makeText(DrawActivity.this, addTxtBox.getText(), Toast.LENGTH_SHORT).show();
                    addedTxtView.setVisibility(View.VISIBLE);
                    txtVal = addTxtBox.getText().toString();
                    imgView.getTxtValue(addTxtBox.getText().toString());
                    addedTxtView.setText(addTxtBox.getText().toString());
                    addedTxtView.setTag(addTxtBox.getText().toString());
                    addTxtBox.setVisibility(View.GONE);
                    try {
                        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                        inputMethodManager.hideSoftInputFromWindow(addTxtBox.getWindowToken(), InputMethodManager.RESULT_UNCHANGED_SHOWN);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    return true;
                }
                return false;
            }
        });
    
    
        resetBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imgView.resetPaths();
            }
        });
    
        undoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imgView.removeLastPath();
            }
        });
    
        saveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bitmap bitmap = imgView.getDrawingCache();
                File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
                path.mkdirs();
                Long tsLong = System.currentTimeMillis()/1000;
                String ts = tsLong.toString();
                File imageFile = new File(path, ts+".png"); // Imagename.png
    
                try{
                    FileOutputStream out = new FileOutputStream(imageFile);
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, out); // Compress Image
                    try {
                        out.flush();
                        out.close();
                    } catch (IOException e){
                        e.printStackTrace();
                    }
    
    
                    // Tell the media scanner about the new file so that it is
                    // immediately available to the user.
                    MediaScannerConnection.scanFile(context,new String[] { imageFile.getAbsolutePath() }, null,new MediaScannerConnection.OnScanCompletedListener() {
                        public void onScanCompleted(String path, Uri uri) {
                            Log.i("ExternalStorage", "Scanned " + path + ":");
                            Log.i("ExternalStorage", "-> uri=" + uri);
    
                        }
                    });
                    Toast.makeText(context,"Saved", Toast.LENGTH_SHORT).show();
    
                    Intent intent = new Intent(DrawActivity.this, MainActivity.class);
                    startActivity(intent);
                } catch(FileNotFoundException e) {
                    Toast.makeText(context,"Error" + e.toString(), Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                }
            }
        });
    
    }
    
    
    
    public void redrawImage() {
        Bitmap bm = imgView.getDrawingCache();
        Bitmap proxy = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(proxy);
        Paint paint = new Paint();
        // paint.setStyle(Paint.Style.STROKE);
        paint.setColor(Color.RED);
        paint.setTextSize(100);
        paint.setAntiAlias(true);
    
        c.drawBitmap(bm, new Matrix(), paint);
        c.drawText(txtVal, imgView.getWidth()+rowX, imgView.getHeight()+rowY, paint);
        imgView.setImageBitmap(proxy);
    }
    
    public void changeColor(View view) {
        Log.d("Vishal selected color", view.getTag().toString());
    
        switch (view.getTag().toString()){
            case "red":
                imgView.setBrushColor(Color.RED);
                break;
    
            case "blue":
                imgView.setBrushColor(Color.BLUE);
                break;
    
            case "green" :
                imgView.setBrushColor(Color.GREEN);
                break;
    
            case "yellow":
                imgView.setBrushColor(Color.YELLOW);
                break;
    
            case "purple":
                imgView.setBrushColor(getResources().getColor(R.color.purple));
                break;
    
            default:
                imgView.setBrushColor(Color.BLACK);
        }
        //
    }
    

  2. activity_draw.xml

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/black" >
    
        <ImageButton
            android:id="@+id/undoBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:src="@drawable/undo"/>
    
        <Button
            android:id="@+id/clearBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Clear"
            android:layout_toLeftOf="@+id/saveBtn"/>
    
        <Button
            android:id="@+id/saveBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Save"
            android:layout_alignParentRight="true"/>
    
    </RelativeLayout>
    
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1.8"
        android:orientation="vertical"
        android:id="@+id/draw_image_linearView">
    
        <RelativeLayout
            android:id="@+id/relativeLayout1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
    
            <com.example.mobilesolution.imgedit.DrawView
                android:id="@+id/frag_home_iv_main"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:adjustViewBounds="true"
                android:scaleType="fitXY"/>
    
            <TextView
                android:id="@+id/drawTextView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:elevation="100dp"
                android:layout_centerInParent="true"
                android:textColor="@android:color/black"
                android:textSize="16dp"
                />
    
            <EditText
                android:id="@+id/addTxt"
                android:layout_centerInParent="true"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:hint="Enter some text"
                android:inputType="textMultiLine"
                android:maxLines="3"
                android:elevation="10dp"/>
    
    
        </RelativeLayout>
    
    </RelativeLayout>
    
    <HorizontalScrollView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fillViewport="true"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:paddingTop="5dp"
        android:scrollbars="none"
        android:layout_weight="0.2">
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
    
            <LinearLayout
                android:layout_width="447dp"
                android:layout_height="match_parent"
                android:gravity="center"
                android:orientation="horizontal"
                android:padding="10dp">
    
                <ImageView
                    android:id="@+id/redBall"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginRight="10dp"
                    android:onClick="changeColor"
                    android:src="@drawable/red_ball"
                    android:tag="red" />
    
                <ImageView
                    android:id="@+id/blueBall"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginRight="10dp"
                    android:onClick="changeColor"
                    android:src="@drawable/blue_ball"
                    android:tag="blue" />
    
                <ImageView
                    android:id="@+id/greenBall"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginRight="10dp"
                    android:onClick="changeColor"
                    android:src="@drawable/green_ball"
                    android:tag="green" />
    
                <ImageView
                    android:id="@+id/yellowBall"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginRight="10dp"
                    android:onClick="changeColor"
                    android:src="@drawable/yellow_ball"
                    android:tag="yellow" />
    
                <ImageView
                    android:id="@+id/purpleBall"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginRight="10dp"
                    android:onClick="changeColor"
                    android:src="@drawable/purple_ball"
                    android:tag="purple" />
    
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginRight="10dp"
                    android:src="@drawable/red_ball" />
    
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginRight="10dp"
                    android:src="@drawable/red_ball" />
    
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginRight="10dp"
                    android:src="@drawable/red_ball" />
    
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginRight="10dp"
                    android:src="@drawable/green_ball" />
    
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginRight="10dp"
                    android:src="@drawable/green_ball" />
    
            </LinearLayout>
        </LinearLayout>
    
    
    </HorizontalScrollView>
    
    
    <RelativeLayout
        android:id="@+id/brushBtnLayout"
        android:layout_width="wrap_content"
        android:layout_height="48dp"
        android:background="@android:color/black">
    
        <ImageView
            android:id="@+id/imageBrush"
            android:layout_width="65dp"
            android:layout_height="37dp"
            android:layout_marginLeft="66dp"
            android:layout_marginStart="66dp"
            android:background="@android:color/white"
            android:src="@drawable/brush"
            android:layout_alignTop="@+id/imageFont"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true" />
    
        <ImageView
            android:id="@+id/imageFont"
            android:layout_width="65dp"
            android:layout_height="37dp"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginEnd="52dp"
            android:layout_marginRight="52dp"
            android:background="@android:color/white"
            android:src="@drawable/font" />
    
    </RelativeLayout>
    

最佳答案

当拖动存在时,您应该设置 XY 坐标,而不是设置边距。

再次更新 放置 View 是您的 TextView 应该放入的位置。这应该包含拖动监听器

frag_home_iv_main.setOnDragListener(new View.OnDragListener() {
            @Override
            public boolean onDrag(View view, DragEvent dragEvent) {
                int action = dragEvent.getAction();
                View viewdrag = (View) dragEvent.getLocalState();
                if(action == DragEvent.ACTION_DRAG_ENTERED){
                    //do something
                }
                else if(action == DragEvent.ACTION_DRAG_EXITED){
                    //do something

                    Log.d("Vishal Drag", "Action is DragEvent.ACTION_DRAG_EXITED");
                    x_cord = (int) event.getX();
                    y_cord = (int) event.getY();
                    viewdrag .setY(y_cord);
                    viewdrag .setX(x_cord);
                }

                else if(action == DragEvent.ACTION_DROP){
                    //do something
                }
                return true;
            }
        });

关于Android-Textview 在拖动操作时消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51510361/

有关Android-Textview 在拖动操作时消失的更多相关文章

  1. 安卓apk修改(Android反编译apk) - 2

    最近因为项目需要,需要将Android手机系统自带的某个系统软件反编译并更改里面某个资源,并重新打包,签名生成新的自定义的apk,下面我来介绍一下我的实现过程。APK修改,分为以下几步:反编译解包,修改,重打包,修改签名等步骤。安卓apk修改准备工作1.系统配置好JavaJDK环境变量2.需要root权限的手机(针对系统自带apk,其他软件免root)3.Auto-Sign签名工具4.apktool工具安卓apk修改开始反编译本文拿Android系统里面的Settings.apk做demo,具体如何将apk获取出来在此就不过多介绍了,直接进入主题:按键win+R输入cmd,打开命令窗口,并将路

  2. ruby - 如何使用 Selenium Webdriver 根据 div 的内容执行操作? - 2

    我有一个使用SeleniumWebdriver和Nokogiri的Ruby应用程序。我想选择一个类,然后对于那个类对应的每个div,我想根据div的内容执行一个Action。例如,我正在解析以下页面:https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=puppies这是一个搜索结果页面,我正在寻找描述中包含“Adoption”一词的第一个结果。因此机器人应该寻找带有className:"result"的div,对于每个检查它的.descriptiondiv是否包含单词“adoption

  3. ruby-on-rails - 如何处理 Grape 中特定操作的过滤器之前? - 2

    我正在我的Rails项目中安装Grape以构建RESTfulAPI。现在一些端点的操作需要身份验证,而另一些则不需要身份验证。例如,我有users端点,看起来像这样:moduleBackendmoduleV1classUsers现在如您所见,除了password/forget之外的所有操作都需要用户登录/验证。创建一个新的端点也没有意义,比如passwords并且只是删除password/forget从逻辑上讲,这个端点应该与用户资源。问题是Grapebefore过滤器没有像except,only这样的选项,我可以在其中说对某些操作应用过滤器。您通常如何干净利落地处理这种情况?

  4. ruby-on-rails - 在 Ruby on Rails 中发送响应之前如何等待多个异步操作完成? - 2

    在我做的一些网络开发中,我有多个操作开始,比如对外部API的GET请求,我希望它们同时开始,因为一个不依赖另一个的结果。我希望事情能够在后台运行。我找到了concurrent-rubylibrary这似乎运作良好。通过将其混合到您创建的类中,该类的方法具有在后台线程上运行的异步版本。这导致我编写如下代码,其中FirstAsyncWorker和SecondAsyncWorker是我编写的类,我在其中混合了Concurrent::Async模块,并编写了一个名为“work”的方法来发送HTTP请求:defindexop1_result=FirstAsyncWorker.new.async.

  5. ruby-on-rails - environment.rb 中设置的常量在开发模式中消失 - 2

    了解Rails缓存如何工作的人可以真正帮助我。这是嵌套在Rails::Initializer.runblock中的代码:config.after_initializedoSomeClass.const_set'SOME_CONST','SOME_VAL'end现在,如果我运行script/server并发出请求,一切都很好。然而,在我的Rails应用程序的第二个请求中,一切都因单元化常量错误而变得糟糕。在生产模式下,我可以成功发出第二个请求,这意味着常量仍然存在。我已通过将以上内容更改为以下内容来解决问题:config.after_initializedorequire'some_cl

  6. ruby - 在 Ruby 中是否有一种惯用的方法来操作 2 个数组? - 2

    a=[3,4,7,8,3]b=[5,3,6,8,3]假设数组长度相同,是否有办法使用each或其他一些惯用方法从两个数组的每个元素中获取结果?不使用计数器?例如获取每个元素的乘积:[15,12,42,64,9](0..a.count-1).eachdo|i|太丑了...ruby1.9.3 最佳答案 使用Array.zip怎么样?:>>a=[3,4,7,8,3]=>[3,4,7,8,3]>>b=[5,3,6,8,3]=>[5,3,6,8,3]>>c=[]=>[]>>a.zip(b)do|i,j|c[[3,5],[4,3],[7,6],

  7. ruby-on-rails - 如何让 Rails View 返回其关联的操作名称? - 2

    我有一个非常简单的Controller来管理我的Rails应用程序中的静态页面:classPagesController我怎样才能让View模板返回它自己的名字,这样我就可以做这样的事情:#pricing.html.erb#-->"Pricing"感谢您的帮助。 最佳答案 4.3RoutingParametersTheparamshashwillalwayscontainthe:controllerand:actionkeys,butyoushouldusethemethodscontroller_nameandaction_nam

  8. Postman测试简单操作 - 2

    1、接口请求基本操作1.1例子tips在view的选项可以zoomin调整窗口字帖大小。1、创建一个测试的workspace,并命名为test2、test后面新增一个addrequest3、选择发送GET,URL为一个开源的https://api.apiopen.top/api/sentences获取每日一句4、点击send查看内容Tips:如果提示出现Error:tunnelingsocketcouldnotbeestablished,statusCode=407错误,参照以下解决办法)关于tunnelingsocketcouldnotbeestablished,cause=getaddri

  9. 【Linux操作系统】——网络配置与SSH远程 - 2

    Linux操作系统——网络配置与SSH远程安装完VMware与系统后,需要进行网络配置。第一个目标为进行SSH连接,可以从本机到VMware进行文件传送,首先需要进行网络配置。1.下载远程软件首先需要先下载安装一款远程软件:FinalShell或者xhell7FinalShellxhell7FinalShell下载:Windows下载http://www.hostbuf.com/downloads/finalshell_install.exemacOS下载http://www.hostbuf.com/downloads/finalshell_install.pkg2.配置CentOS网络安装好

  10. ruby - Ruby 语言可以用来构建操作系统吗? - 2

    Ruby语言是否可以用于创建全新的移动操作系统或桌面操作系统,即是否可以用于系统编程? 最佳答案 嗯,现在有一些操作系统使用比C更高级的语言。基本上,ruby解释器本身需要用一些低级的东西来编写,并且需要一些引导加载代码将功能齐全的ruby​​解释器作为独立内核加载到内存中。一旦ruby​​解释器被引导并以内核模式(或innerrings之一)运行,就没有什么可以阻止您在其上构建整个操作系统。不幸的是,它可能会很慢。每个操作系统功能的垃圾收集可能会相当引人注目。ruby解释器将负责任务调度和网络堆栈等基本事情,使用垃圾收集框架会大大

随机推荐