使用上下文菜单在编辑器中插入文本和图片

时间:2019-01-28 12:23:37

标签: android

我正在尝试学习android编程。我已经成功创建了屏幕并在其中进行了导航。现在,我正在尝试一些冒险的事情。

我正在创建一个类似MS Word的文本编辑器,您可以在其中使用上下文菜单键入文本并从图库中插入图像。

enter image description here

我通过了链接Get/pick an image from Android's built-in Gallery app programmatically。但是我有几个问题。

  1. EditText是否适合此控件?
  2. 如何从光标所在的位置调用上下文菜单?
  3. 如何将图像粘贴到光标所在的位置?

任何对此的见解都会有很大帮助。

1 个答案:

答案 0 :(得分:1)

好的,让我们一个接一个地解决它们:

  

EditText是否适合此控件?

当然,除非您要像MS word一样创建应用程序,否则它将完美运行。

诸如多个“编辑文本”之类的内容可以用作单词的不同页面,并且您可以为每个“页面”指定长度和宽度,并具有常用的XML属性,并用view分隔它们以获取页面的结尾并开始新的页面机制。

现在要使用光标添加图片,您只需创建一个上下文菜单,然后以编程方式将该图片添加到布局中,即可结束edit text,创建image view并继续其他操作edit text,让我们看看如何做到这一点:

首先打开上下文菜单:

@Override
public void onCreateContextMenu(ContextMenu menu, View v,
                            ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
if(item.getTitle().equals("Insert Image") ){

InsertImage(Uri imageUri);
      }
}
  

如何从光标所在的位置调用上下文菜单?

     

如何将图像粘贴到光标所在的位置?

您需要实现一个称为View.OnCreateContextMenuListener的操作,该操作可以在您按任意位置时用long click完成,因此您将看到您要么必须实现另一种方法来获取光标所在的位置,然后将您的编辑文本分为两个不同的edit text并插入图片,否则您将必须始终按照图片的提示将图片放在文本视图下

第二,创建上下文菜单时,我们可以调用一个名为“ InsertImage”的方法,该方法带有从menuInflater传递的Uri参数或在您的类中定义为变量,以创建一个ImageView EditText假设您的父级布局是线性布局:

LinearLayout LLayout = findViewById(R.id.linearLayout);

ImageView mImageView = new ImageView(this);
mImageView.setLayoutParams(new LinearLayout.LayoutParams(
                                     LinearLayout.LayoutParams.WRAP_CONTENT,
                                     LinearLayout.LayoutParams.WRAP_CONTENT));

LLayout.addView(mImageView);

在完成方法“ InsertImage”之后,您可以返回一个boolean,如果图像已上传,则返回edit Text,如果不是,则返回true,那么您将创建另一个方法来像imageView一样开始一个新的removeView,但是如果未上传,则可以像addView一样调用 <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/nestedScrollView" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/text_gray" android:paddingBottom="20dp" android:paddingLeft="20dp" android:paddingRight="20dp" android:paddingTop="20dp"> <android.support.v4.widget.NestedScrollView android:layout_width="match_parent" android:layout_height="match_parent"> // Your other Code here..... </android.support.v4.widget.NestedScrollView> </android.support.constraint.ConstraintLayout>