Giter Club home page Giter Club logo

android-rteditor's Introduction

Android-RTEditor

License Demo App

The Android RTEditor is a rich text editor component for Android that can be used as a drop in for EditText.

Images

Features

The editor offers the following character formatting options:

  • Bold
  • Italic
  • Underline
  • Strike through
  • Superscript
  • Subscript
  • Different fonts
  • Text size
  • Text color
  • Background color
  • Undo/Redo

It also supports the following paragraph formatting:

  1. Numbered
  • Bullet points
    • Indentation
    Left alignment
    Center alignment
    Right alignment

Setup

Dependencies

Add this to your Gradle build file: Groovy

dependencies {
    implementation 'com.1gravity:android-rteditor:1.8.0'
}

Kotlin

dependencies {
    implementation("com.1gravity:android-rteditor:1.8.0")
}

Manifest

Add this to your manifest:

<provider
    android:name="androidx.core.content.FileProvider"
    tools:replace="android:authorities"
    android:authorities="${applicationId}.provider"/>

Proguard

If you use Proguard in your app, please add the following lines to your configuration file:

-keepattributes Signature
-keepclassmembers class * extends com.onegravity.rteditor.spans.RTSpan {
    public <init>(int);
}

The "Signature" attribute is required to be able to access generic type, which the rich text editor code does:

protected BooleanEffect() {
    Type[] types = ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments();
    mSpanClazz = (Class<? extends RTSpan<Boolean>>) types[0];
}

Theming

The toolbar uses a couple of custom attributes that need to be defined or it will crash when being inflated. You need to use a theme based on either RTE_ThemeLight or RTE_ThemeDark or define all rich text editor attributes (rte_toolbar_themes.xml) in your own theme. These two themes inherit from Theme.AppCompat.Light / Theme.AppCompat.

Make sure to call setTheme before setContentView (or set the theme in the manifest):

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // set theme before calling setContentView!
    setTheme(R.style.ThemeLight);

    // set layout
    setContentView(R.layout.your_layout);

The 3 main components

RTEditText

is the EditText drop in component. Add it to your layout like you would EditText:

<com.onegravity.rteditor.RTEditText
    android:id="@+id/rtEditText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:imeOptions="actionDone|flagNoEnterAction"
    android:inputType="textMultiLine|textAutoCorrect|textCapSentences" />

In code you would typically use methods to set and get the text content:

  • set text: RTEditText.setRichTextEditing(true, "My content");
  • get text: RTEditText.getText(RTFormat.HTML)

RTToolbar

is an interface for the toolbar used to apply text and paragraph formatting and other features listed above. The actual RTToolbar implementation is in a separate module and is a scrollable ribbon but alternative implementations aren't too hard to realize (popup, action buttons, floating buttons...). The toolbar implementation is easy to integrate into your layout:

<include android:id="@+id/rte_toolbar_container" layout="@layout/rte_toolbar" />

or if you want to have two ribbons for character and paragraph formatting:

<LinearLayout
    android:id="@+id/rte_toolbar_container"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <include layout="@layout/rte_toolbar_character" />
    <include layout="@layout/rte_toolbar_paragraph" />

</LinearLayout>

Note that inflating the toolbar might take a moment (noticable) on certain devices because the included icons are high-resolution and each one comes in three different states (pressed, checked, normal). There's no workaround for this except using different icons with lower resolution.

In code you'd typically not interact with the toolbar (see RTManager below for the one exception).

RTManager

is the glue that holds the rich text editors (RTEditText), the toolbar and your app together. Each rich text editor and each toolbar needs to be registered with the RTManager before they are functional. Multiple editors and multiple toolbars can be registered. The RTManager is instantiated by your app in code usually in the onCreate passing in an RTApi object that gives the rich text editor access to its context (your app). A typical initialization process looks like this (normally in the onCreate method):

// create RTManager
RTApi rtApi = new RTApi(this, new RTProxyImpl(this), new RTMediaFactoryImpl(this, true));
RTManager rtManager = new RTManager(rtApi, savedInstanceState);

// register toolbar
ViewGroup toolbarContainer = (ViewGroup) findViewById(R.id.rte_toolbar_container);
RTToolbar rtToolbar = (RTToolbar) findViewById(R.id.rte_toolbar);
if (rtToolbar != null) {
    rtManager.registerToolbar(toolbarContainer, rtToolbar);
}

// register editor & set text
RTEditText rtEditText = (RTEditText) findViewById(R.id.rtEditText);
rtManager.registerEditor(rtEditText, true);
rtEditText.setRichTextEditing(true, message);

To retrieve the edited text in html format you'd do:

String text = rtEditText.getText(RTFormat.HTML);

The RTManager also needs to be called in onSaveInstanceState and in onDestroy:

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    mRTManager.onSaveInstanceState(outState);
}

@Override
public void onDestroy() {
    super.onDestroy();
    
    mRTManager.onDestroy(isFinishing());
}

The isSaved parameter passed into RTManager.onDestroy(boolean) is important. If it's true then media files inserted into the text (images at the moment) will remain untouched. If the parameter is false (text content is dismissed), media files will be deleted. Note that the rich text editor copies the original file to a dedicated area according to the MediaFactory configuration, meaning the original will remain untouched.

RTApi

If you read the previous section ("The 3 main components") you might have noticed the RTApi object. The RTApi is a convenience class giving the various rich text editor components access to the application context and to RTProxy and RTMediaFactory methods.

RTApi rtApi = new RTApi(this, new RTProxyImpl(this), new RTMediaFactoryImpl(this, true));

Context

The first parameter is merely a Context object (Application or Activity context). The RTApi will only store the Application context so no issue with leaking the Activity context here.

RTProxy

The RTProxy allows the rich text editor to call Activity related methods like:

  • startActivityForResult/runOnUiThread and Toast methods: for picking images to embed in the text
  • Fragment related methods: for the link dialog (LinkFragment)

RTProxyImpl is the standard implementation for RTProxy and there's usually no need to use a custom implementation. RTProxyImpl stores the Activity context in a SoftReference.

RTMediaFactory

The most interesting class is RTMediaFactory. By overriding it, different storage scenarios for embedded images (and potentially videos and audio files in the future) can be implemented (SQLite database, file system, cloud storage, access through ContentProvider etc.).

More details can be found here

Fonts

The rich text editor supports fonts that are part of the Android device it's running on. It's reading all ttf fonts in the /system/fonts, /system/font and /data/fonts and shows them in the editor.

A lot of frequently used fonts have a copyright and can therefore not be included in this library but you can use any true type font you want by adding them to the assets folder of the demo app (just make sure you don't infringe on someone else's copyright). The fonts can be put anywhere in the assets folder (root or subdirectories). Since reading the directory structure of the assets folder during run-time is pretty slow (see here) a Gradle script generates an index of all ttf files during build time. In order to create that file during build time, please copy the following code to your build.gradle:

task indexAssets {
    description 'Index main.kotlin.Build Variant assets for faster lookup by AssetManager'

    ext.assetsSrcDir = file( "${projectDir}/src/main/assets" )

    inputs.dir assetsSrcDir

    doLast {
        android.applicationVariants.each { target ->
            // create index
            def contents = ""
            def tree = fileTree(dir: "${ext.assetsSrcDir}", include: ['**/*.ttf'], exclude: ['**/.svn/**', '*.index'])
            // use this instead if you have assets folders in each flavor:
            // def tree = fileTree(dir: "${ext.variantPath}", exclude: ['**/.svn/**', '*.index'])
            tree.visit { fileDetails ->
                contents += "${fileDetails.relativePath}" + "\n"
            }

            // create index file
            def assetIndexFile = new File("${ext.assetsSrcDir}/assets.index")
            assetIndexFile.write contents
        }
    }
}

indexAssets.dependsOn {
    tasks.matching { task -> task.name.startsWith( 'merge' ) && task.name.endsWith( 'Assets' ) }
}

tasks.withType( JavaCompile ) {
   compileTask -> compileTask.dependsOn indexAssets
}

indexAssets

Note that loading the fonts can take a moment. That's why you should pre-load them in your Application class (it's an asynchronous call):

FontManager.preLoadFonts(Context);

Demo project

The project consists of four different modules:

  • ColorPicker: a color picker based on this: https://github.com/LarsWerkman/HoloColorPicker. The RTEditor uses an enhanced version that allows to enter ARGB values, includes a ColorPickerPreference that can be used in preference screens and shows a white and gray chessboard pattern behind the color visible when the the alpha channel is changed and the color becomes (partly) transparent.
  • RTEditor: the actual rich text editor (excluding the toolbar implementation).
  • RTEditor-Toolbar: the toolbar implementation.
  • RTEditor-Demo: this module isn't part of the actual rich text editor component but contains a sample app that shows how to use the component.

The demo app can also be found on Google Play: Demo App

Issues

If you have an issues with this library, please open a issue here: https://github.com/1gravity/Android-RTEditor/issues and provide enough information to reproduce it reliably. The following information needs to be provided:

  • Which version of the SDK are you using?
  • Which Android build are you using? (e.g. MPZ44Q)
  • What device are you using?
  • What steps will reproduce the problem? (Please provide the minimal reproducible test case.)
  • What is the expected output?
  • What do you see instead?
  • Relevant logcat output.
  • Optional: Link to any screenshot(s) that demonstrate the issue (shared privately in Drive.)
  • Optional: Link to your APK (either downloadable in Drive or in the Play Store.)

License

Copyright 2015-2023 Emanuel Moecklin

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

android-rteditor's People

Contributors

1gravity avatar android-outliner avatar arpitgoyal2008 avatar kim1059 avatar long1eu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

android-rteditor's Issues

get selected text in HTML format

Hey! I'm trying to get selected text from the Editor but i'm just getting the select text without HTML format.
This is the code:
startSelection = mRTMessageField.getSelectionStart(); endSelection = mRTMessageField.getSelectionEnd(); String selectedText = mRTMessageField.getText(RTFormat.HTML).substring(startSelection, endSelection);

When i try to create a new string parsing the html string with the select text i'm getting the position without html and the selected text is not completed because the position of plain text is different in html format.

This is my logcat when I've selected the text "My first Text!":

01-28 13:36:41.555 18456-18456/com.ufcspa.unasus.appportfolio D/Processingย text:: finding selected text:<b>my</b> firs in text:This is <b>my</b> first <b>Text</b>! 01-28 13:36:41.557 18456-18456/com.ufcspa.unasus.appportfolio D/Processingย text:: selected text starts at position '8' ends at position '22' 01-28 13:36:41.557 18456-18456/com.ufcspa.unasus.appportfolio D/Processingย text:: substring generated:<b>my</b> firs

The selected text have 14 characters "My first Text!" but the string selected was "<b>my</b> firs"

Is there any way to get the selected text in HTML form?

Thanks!

Error using Fragments

Hi, i am trying to use your editor inside a fragment, but whenever i change the screen orientation from landscape to portrait or vice versa, the application crashes with this error:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app.Activities.MainActivity}: java.lang.IllegalStateException: The RTMediaFactory is null. Please make sure to register the editor at the RTManager before using it.

This is my code:
FragmentRTEditor.txt

Other problem is that, pick image and take pictures button are not working using the toolbar implementation that comes with the project. I have to add something else to work? Or i am doing something wrong? I added the gradle dependency and use this code that a already provided.

There is any way to add video in the editor?

Thanks!

Can't setRichTextEditing OnActivityResult Android?

I have problem on my App. I Can't setRichTextEditing OnActivityResult.

But I always get value from second Class. this my code on First Class :

 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == 1) {

            Log.v("requestCode","1");

            if(resultCode == Activity.RESULT_OK){

                Log.v("RESULT_OK","Ya");
                String target=data.getStringExtra(Variabel.target);
                if(target.equals("isi_artikel")){
                    s_isi_artikel=data.getStringExtra(Variabel.content);
                    RTEditText isi_artikel=(RTEditText) findViewById(R.id.isi_artikel);
                    isi_artikel.setRichTextEditing(true,s_isi_artikel);
                    Log.v("s_isi_artikel",s_isi_artikel); // always get from second class
                }
            }
            if (resultCode == Activity.RESULT_CANCELED) {

                Log.v("RESULT_OK","No");
            }
        }
    }

so how to fix it ?

How to load an image into the RTEditor from a link?

I've seen the sample app and some.of the code but I can't or maybe I failed to find how to insert an image into the RTEditor from a url

EDIT :
I've scoured around the source code, but I still can't find a method or implementation that could be used. Though, I could download the image and save it into a storage location that I can reference then create an RTImage object out of it, the problem now is how to reference the link used in the actual text I would get from the editor.

Also, is there a way to remove the loading of fonts from the device? I have an app that has multiple fragments and one of those fragments houses the RTEditor. I initialize the RTEditor in the onCreate method so the transition gets stuck for about 1-2 seconds before showing the actual fragment. I can't find any method to "turn off" this the font style feature.

Rendering Problems

Please tell me how to solve this problem?

<LinearLayout
        android:id="@+id/rte_toolbar_container"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <include layout="@layout/rte_toolbar_character" />
        <include layout="@layout/rte_toolbar_paragraph" />

    </LinearLayout>

Rendering Problems java.lang.NullPointerException ย ย at com.onegravity.rteditor.fonts.FontManager.listFontFiles(FontManager.java:185) ย ย at com.onegravity.rteditor.fonts.FontManager.listFontFiles(FontManager.java:178) ย ย at com.onegravity.rteditor.fonts.FontManager.getAssetFonts(FontManager.java:158) ย ย at com.onegravity.rteditor.fonts.FontManager.getFonts(FontManager.java:97) ย ย at com.onegravity.rteditor.toolbar.HorizontalRTToolbar.getFontItems(HorizontalRTToolbar.java:213) ย ย at com.onegravity.rteditor.toolbar.HorizontalRTToolbar.onFinishInflate(HorizontalRTToolbar.java:177) ย ย at android.view.LayoutInflater.rInflate_Original(LayoutInflater.java:844) ย ย at android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.java:70) ย ย at android.view.LayoutInflater.rInflate(LayoutInflater.java:811) ย ย at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798) ย ย at android.view.LayoutInflater.rInflate_Original(LayoutInflater.java:838) ย ย at android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.java:70) ย ย at android.view.LayoutInflater.rInflate(LayoutInflater.java:811) ย ย at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798) ย ย at android.view.LayoutInflater_Delegate.parseInclude(LayoutInflater_Delegate.java:197) ย ย at android.view.LayoutInflater.parseInclude(LayoutInflater.java:879) ย ย at android.view.LayoutInflater.rInflate_Original(LayoutInflater.java:831) ย ย at android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.java:70) ย ย at android.view.LayoutInflater.rInflate(LayoutInflater.java:811) ย ย at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798) ย ย at android.view.LayoutInflater.rInflate_Original(LayoutInflater.java:838) ย ย at android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.java:70) ย ย at android.view.LayoutInflater.rInflate(LayoutInflater.java:811) ย ย at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798) ย ย at android.view.LayoutInflater.inflate(LayoutInflater.java:515) ย ย at android.view.LayoutInflater.inflate(LayoutInflater.java:394)

At the time of launch activity.

E/AssetIndex: assets.index
java.io.FileNotFoundException: assets.index
at android.content.res.AssetManager.openAsset(Native Method)
at android.content.res.AssetManager.open(AssetManager.java:316)
at android.content.res.AssetManager.open(AssetManager.java:290)
at com.onegravity.rteditor.fonts.AssetIndex.getAssetIndex(AssetIndex.java:46)
at com.onegravity.rteditor.fonts.FontManager.getAssetFonts(FontManager.java:156)
at com.onegravity.rteditor.fonts.FontManager.getFonts(FontManager.java:97)
at com.onegravity.rteditor.toolbar.HorizontalRTToolbar.getFontItems(HorizontalRTToolbar.java:213)
at com.onegravity.rteditor.toolbar.HorizontalRTToolbar.onFinishInflate(HorizontalRTToolbar.java:177)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:763)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:839)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:745)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:256)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)
at com.cloudstechnologies.smartypro.activities.ActivityTaskEdit.onCreate(ActivityTaskEdit.java:73)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)

<Strike> Bug

To reproduce

  1. Load/Set the following html to editor
<strike>testing abc</strike>
 mRteEditText.setRichTextEditing(true, "<strike>testing abc</strike>");
  1. The editor is unable to enable the Strike toolbar button select state even though it is properly parsed into spans. Output of the editor is also correct so the strike span is there but the RTManager.java effect.existsInSelection(editor) is evaluating to false for some reason.

Select Image OOME

Hi,

i choose my photos,

and it's crush by oome...

how to fix this???

Adding bullets in empty line doesn't work

I want to start an unordered list (bullets), so:

  1. I press the "bullet" button -> it changes its state to activated, but no bullet is drawn
  2. I start typing -> there's still no bullet and the button changes its state to not activated
    The only way to add a bullet is to create the line of text first and then apply a bullet to it.

If changing the behaviour is not easy/possible, there should be at least an opportunity to tell the user how to add a bullet, so e.g. when the "bullet" button is pressed and the cursor is on an empty line, the button shouldn't be activated, but instead the edit text should notify the client application about this situation. The client application can now e.g. display a tooltip informing a user about the procedure of inserting bullets.

DemoApp code is different from the code that came with gradle.

Hi, the Background Color Effect class that is inside the demo app don't have code but in the same class in my project have. Is there any difference between the implementation that you are using in the demo app and the the version that we have in Gradle?

Thanks for the help.

Here is the code that i have in my project:

package com.onegravity.rteditor.effects;

import android.text.Spannable;
import android.text.Spanned;
import android.text.style.BackgroundColorSpan;

import com.onegravity.rteditor.RTEditText;
import com.onegravity.rteditor.utils.Selection;

import java.util.ArrayList;
import java.util.List;

/**
 * Background color
 */
public class BackgroundColorEffect extends Effect<Integer> {

    @Override
    public List<Integer> valuesInSelection(RTEditText editor, int spanType) {
        Selection expandedSelection = getExpandedSelection(editor, spanType);

        List<Integer> result = new ArrayList<Integer>();
        for (BackgroundColorSpan span : getSpans(editor.getText(), expandedSelection)) {
            result.add(span.getBackgroundColor());
        }
        return result;
    }

    /**
     * @param color If the color is Null then the background color will be removed
     */
    public void applyToSelection(RTEditText editor, Integer color) {
        Selection selection = new Selection(editor);
        Spannable str = editor.getText();

        for (BackgroundColorSpan span : getSpans(str, selection)) {
            int spanStart = str.getSpanStart(span);
            if (spanStart < selection.start()) {
                str.setSpan(new BackgroundColorSpan(span.getBackgroundColor()), spanStart, selection.start(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            int spanEnd = str.getSpanEnd(span);
            if (spanEnd > selection.end()) {
                str.setSpan(new BackgroundColorSpan(span.getBackgroundColor()), selection.end() + 1, spanEnd, Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
            }
            str.removeSpan(span);
        }

        if (color != null) {
            // if the style is enabled add it to the selection (add the leading and trailing spans too if there are any)
            str.setSpan(new BackgroundColorSpan(color), selection.start(), selection.end(),
                    selection.start() == selection.end() ? Spanned.SPAN_INCLUSIVE_INCLUSIVE : Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
        }
    }

    @Override
    protected BackgroundColorSpan[] getSpans(Spannable str, Selection selection) {
        return str.getSpans(selection.start(), selection.end(), BackgroundColorSpan.class);
    }

}

Material Dialog duplicate entry

I get this error when compile the project, I'm already using material dialog library and want to exclude the one which you are using in this project. Please guide how can i exclude while adding dependencies

Error:Execution failed for task ':app:packageAllDebugClassesForMultiDex'.

java.util.zip.ZipException: duplicate entry: com/afollestad/materialdialogs/BuildConfig.class

Err: Resource is not a Drawable

Thanks a lot for sharing this code!

I am getting this error when I am inflating the layout with the toolbar in the onCreateView method of the fragment.

Binary XML file line #33: Error inflating class com.onegravity.rteditor.toolbar.RTToolbarImageButton
Caused by: android.content.res.Resources$NotFoundException: Resource is not a Drawable (color or path): TypedValue{t=0x2/d=0x7f0100f3 a=-1}

Not sure if I am doing something wrong or its an issue with the code.

Switching alignment on an empty new line, alignment bug

When entering something into the first line, pressing enter and thus switching to the second line and then altering the alignment results in the first line taking on the alignment of the second line.
When something is entered into the second line, the first line jumps back to its original alignment.

Also gets exported to HMTL carrying the false alignment:
Before entering something: <div align="center">TEXT</div><div align="center"></div>
After entering something: <div align="right">TEXT</div><div align="center">T</div>

Change files path

Hi! I want to change where the images are saved when using the editor. I have read your documentation, but i dont know how i can do that. Can you help me, please?

BR Tag

Hey! Man, i noticed that when you have a background color tag and you press enter to create another line (a br tag is inserted) the background color tag is duplicated like this:

<font id='1' style="background-color:#70e7d0">Test 1<br/>
<id='1' /font><font id='1' style="background-color:#70e7d0">Test 2<id='1' /font>

Why this happens? Why it can't be like this:

<font id='1' style="background-color:#70e7d0">Test 1<br/>Test 2<id='1' /font>

Thanks!

Underline issue

The underline icon is activated (highlighted) without clicking on it. The text is underlined until you enter space then the underline is removed and the button is de-activated. This happens again as you continue typing.

Saved Images

Hey man,

I was wondering where the captured images are being saved? Can i change their path?

Thanks

Image loading error

Hello,

I am using RTEditor library in my Android App, but when I load an image from device gallery, I get the below error message. The same error is got, when I use the library Demo app.
Could you please help me, how to fix it.

Best,

01-11 11:54:16.385: E/AndroidRuntime(27585): Caused by: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=101, result=-1, data=Intent { dat=content://media/external/images/media/25054 (has extras) }} to activity {com.mqb.pashtostanderdfonts/com.onegravity.rteditor.media.choose.MediaChooserActivity}: com.onegravity.rteditor.api.RTApi$IncorrectInitializationException: Create an RTApi object before calling RTApi.getApplicationContext()

Issue with applying different styles without spacing

@1gravity
Hello, I've faced with a problem if I start typing with default style, after that I select for example bold, and I will not do a space the bold style will not be applied, it will continue display default style and if I add a space and continue typing - the text will become bold. The same issue happens for all styles (bold, underline, etc...)

Thanks in advance, Roman.

Error inflating class com.onegravity.rteditor.toolbar.HorizontalRTToolbar

hi

I face this error when trying to use your RichText editor.
can you advice me my mistake is?

gradle file
apply plugin: 'com.android.application'

android {
compileSdkVersion 23
buildToolsVersion "23.0.1"

defaultConfig {
    applicationId "facebooklogin.myapplication"
    minSdkVersion 21
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.1gravity:android-rteditor:1.1.6'
}

Activity.xml

<include android:id="@+id/rte_toolbar_container" layout="@layout/rte_toolbar" />

<ScrollView
    android:id="@+id/rte_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentTop="true"
    android:layout_above="@id/rte_toolbar_container"
    android:layout_margin="4dp"
    android:fillViewport="true"
    android:scrollbarStyle="insideOverlay" >

    <com.onegravity.rteditor.RTEditText
        android:id="@+id/rtEditText_1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="top"
        android:hint="test"
        android:imeOptions="actionDone|flagNoEnterAction"
        android:inputType="textMultiLine|textAutoCorrect|textCapSentences" />

</ScrollView>

Activty java file
package facebooklogin.myapplication;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    try {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    catch(Exception e) {

    String sf = e.toString();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

CSS styles in Android Rich Text Editor not working

I had been working on reading Docx files using Docx4j library when converted docx content to html and read it through webview. However, the same html code when I tried loading in Android Rich Text Editor I did not get any format of text nor the images. I found The css styles were commented so I removed that as well using string html using below code:
(Posted same question on stackoverflow : http://stackoverflow.com/questions/31359811/css-styles-in-android-rich-text-editor-not-working)
html = html.replace("", "");
This also did not fix my issue and I receive the same plain text without format. html however contains well defined css code. A snapshot of same is here:

I have checked html does work in RTEditor:

Code:

 String subject = "";Spanned description = null;
 String message = null;
 String signature = null;String withCharacters;
 String tsx="";String html = null;
 if (savedInstanceState == null) {
    Intent intent = getIntent();
    subject = getIntent().getStringExtra("textReportFileName");
    message = getStringExtra(intent, "message");
    signature = getStringExtra(intent, "signature");
    mUseDarkTheme = intent.getBooleanExtra("mUseDarkTheme", false);
    mSplitToolbar = intent.getBooleanExtra("mSplitToolbar", false);
} else {
    subject = savedInstanceState.getString("subject", "");
    mUseDarkTheme = savedInstanceState.getBoolean("mUseDarkTheme", false);
    mSplitToolbar = savedInstanceState.getBoolean("mSplitToolbar", false);
}

final long startTime = System.currentTimeMillis();
final long endTime;
try {
    final LoadFromZipNG loader = new LoadFromZipNG();
    WordprocessingMLPackage wordMLPackage = (WordprocessingMLPackage)loader.get(new FileInputStream(new File(Environment.getExternalStorageDirectory()+"/"+getIntent().getStringExtra("textReportFileName"))));
    //getIntent().getStringExtra("textReportFileName")
    String IMAGE_DIR_NAME = "images";

    String baseURL = this.getDir(IMAGE_DIR_NAME, Context.MODE_WORLD_READABLE).toURL().toString();
    System.out.println(baseURL); // file:/data/data/com.example.HelloAndroid/app_images/

    // Uncomment this to write image files to file system
    ConversionImageHandler conversionImageHandler = new AndroidFileConversionImageHandler( IMAGE_DIR_NAME, // <-- don't use a path separator here
            baseURL, false, this);

    // Uncomment to use a base 64 encoded data URI for each image
    // ConversionImageHandler conversionImageHandler = new AndroidDataUriImageHandler();

    HtmlExporterNonXSLT withoutXSLT = new HtmlExporterNonXSLT(wordMLPackage, conversionImageHandler);

    html = XmlUtils.w3CDomNodeToString(withoutXSLT.export());
    html = html.replace("<!--", "");
    html = html.replace("-->", "");
    withCharacters = StringEscapeUtils.unescapeHtml(html);
    description = Html.fromHtml(withCharacters);

    //WebView webview = (WebView)this.findViewById(R.id.webpage);
    //webview.loadDataWithBaseURL(baseURL, html , "text/html", null, null);


    // TabHost mTabHost = getTabHost();
    // mTabHost.addTab(mTabHost.newTabSpec("tab_test2").setIndicator("Web Page").setContent(R.id.webpage));
    // mTabHost.addTab(mTabHost.newTabSpec("tab_test1").setIndicator("View Source").setContent(tv.getId()));
    // mTabHost.setCurrentTab(0);

} catch (Exception e) {
    e.printStackTrace();
    Toast.makeText(getApplicationContext(),"Invalid Format Exception",Toast.LENGTH_SHORT).show();
} finally {
    endTime = System.currentTimeMillis();
}
final long duration = endTime - startTime;
System.err.println("Total time: " + duration + "ms");


message = "<html><head><style>div{background-color: blue}</style></head><body>Hello <h1>How are you?</h1> <p>My name is <b> Abhishek</b></p><div>Whats up?</div>\n" +"<img src=\"http://www.w3schools.com/images/colorpicker.png\"/>\n" +"</body></html>";

Toast.makeText(getApplicationContext(),message,Toast.LENGTH_SHORT).show();

// set theme
setTheme(mUseDarkTheme ? R.style.ThemeDark : R.style.ThemeLight);

super.onCreate(savedInstanceState);

// set layout
setContentView(mSplitToolbar ? R.layout.rte_demo_2 : R.layout.rte_demo_1);

// initialize rich text manager
RTApi rtApi = new RTApi(this, new RTProxyImpl(this), new RTMediaFactoryImpl(this, true));
mRTManager = new RTManager(rtApi, savedInstanceState);

ViewGroup toolbarContainer = (ViewGroup) findViewById(R.id.rte_toolbar_container);

// register toolbar 0 (if it exists)
HorizontalRTToolbar rtToolbar0 = (HorizontalRTToolbar) findViewById(R.id.rte_toolbar);
if (rtToolbar0 != null) {
    mRTManager.registerToolbar(toolbarContainer, rtToolbar0);
}

// register toolbar 1 (if it exists)
HorizontalRTToolbar rtToolbar1 = (HorizontalRTToolbar) findViewById(R.id.rte_toolbar_character);
if (rtToolbar1 != null) {
    mRTManager.registerToolbar(toolbarContainer, rtToolbar1);
}

// register toolbar 2 (if it exists)
HorizontalRTToolbar rtToolbar2 = (HorizontalRTToolbar) findViewById(R.id.rte_toolbar_paragraph);
if (rtToolbar2 != null) {
    mRTManager.registerToolbar(toolbarContainer, rtToolbar2);
}

// set subject
mSubjectField = (EditText) findViewById(R.id.subject);
mSubjectField.setText(subject);

// register message editor
mRTMessageField = (RTEditText) findViewById(R.id.rtEditText_1);
mRTManager.registerEditor(mRTMessageField, true);
if (message != null) {
    mRTMessageField.setRichTextEditing(true, message);
}

// register signature editor
mRTSignatureField = (RTEditText) findViewById(R.id.rtEditText_2);
mRTManager.registerEditor(mRTSignatureField, true);
if (signature != null) {
    mRTSignatureField.setRichTextEditing(true, signature);
}

mRTMessageField.requestFocus();

}

Update:
It doesn't show any styles be it inline or external. Now only way is to read the docx file character by character and check font of each and add it suitably in RTEditor.

Cursor takes height same as selected image height

I am using this lib in my own project but getting an issue. When I select image then cursor size increase as image size. I tried very often but not got any
screenshot from 2016-04-21 17 33 09
solution please tell me how can i fix this problem.

With Regards
Arvind Kumar

Unable to change the Actionbar's Title and Home/Back arrow color

I'm trying to change the title color in action using the style

<style name="ThemeLight" parent="@style/RTE_ThemeLight"> @color/actionbar_color @color/actionbar_color @color/actionbar_color @color/white @style/MyActionBarTitleText </style>
<style name="MyActionBarTitleText" parent="@style/TextAppearance.AppCompat.Widget.ActionBar.Title">
    <item name="android:textColor">@color/white</item>
</style>

but it does not work for me. Please guide.

Custom Theme

an app im making uses appcompat support lib v19
but when i put Android-RTEditor in my dependencies my custom theme disappear... before it only disappears when i use appcompatsupport libv21 and up... could you explain why this happen when im just putting the dependency..

Supporting RTL languages

Thank you for your great efforts, this works perfectly on LTR languages.
But when we use RTL languages, the direction is reversed, the opposite of the alignment icons.
If you can please fix it.
Thanks.

Modify HTML tag

Hey! I am trying to create a custom tag for my application. I want to create something like this:

<font id="1" style="background-color:#000000">Teste</font id="1">

add a identifier id="1" inside the HTML tag. But i can't understand how i can alter the tags in your code. Is there any way?

Thanks

RTApi methods in onCreate Method affects the activity performace (Black screen for sometime before activity start)

Here is my code

protected void onCreate(Bundle savedInstanceState) {
setTheme(R.style.ThemeLight);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app_form);
RTApi rtApi = new RTApi(this, new RTProxyImpl(this), new RTMediaFactoryImpl(this, true));
rtManager = new RTManager(rtApi, savedInstanceState);
ViewGroup toolbarContainer = (ViewGroup) findViewById(R.id.rte_toolbar_container);
RTToolbar rtToolbar0 = (RTToolbar) findViewById(R.id.rte_toolbar);
if (rtToolbar0 != null) {
rtManager.registerToolbar(toolbarContainer, rtToolbar0);
}

    RTToolbar rtToolbar1 = (RTToolbar) findViewById(R.id.rte_toolbar_character);
    if (rtToolbar1 != null) {
        rtManager.registerToolbar(toolbarContainer, rtToolbar1);
    }

    // register toolbar 2 (if it exists)
    RTToolbar rtToolbar2 = (RTToolbar) findViewById(R.id.rte_toolbar_paragraph);
    if (rtToolbar2 != null) {
        rtManager.registerToolbar(toolbarContainer, rtToolbar2);
    }
    initialize();
}

When i start this activity, A black empty screen become appear for 4-5 seconds and then activity starts. Is there any problem in my implementation?

problem with setRichTextEditing

hi
when i use "setRichTextEditing" in programming side , dont implementation conditions like "Bold" , "italics".

how i fix this problem??

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.