Проект GSYRichText
Данный проект представляет собой перенос и разработку на основе открытого проекта GSYRickText для операционной системы HarmonyOS. Версия переноса: v2.0.2.
Проект поддерживает функции, подобные тем, что есть в социальной сети Weibo: текст с эффектами, эмодзи, @упоминание людей, темы, URL-ссылки и т. д. В демоверсии показаны различные эффекты ввода текста.
// Ядро
implementation project(':draweetext')
implementation project(':xedittext')
В файле build.gradle в разделе repositories добавьте:
mavenCentral()
В модуле build.gradle добавьте в раздел dependencies:
implementation 'com.gitee.ts_ohos:draweetext:1.0.0'
implementation 'com.gitee.ts_ohos:xedittext:1.0.0'
Класс RichTextFactory используется для управления стилем форматированного текста (цвет и размер шрифта), а также для добавления форматированного текста.
Пример использования:
/**
* RichTextFactory Constructor
*
* @param context context
*/
public RichTextFactory(Context context) {
this.richTextBuilder = new RichTextBuilder();
this.textFormClickable = new TextForm();
this.textFormNormal = new TextForm();
RgbColor colorBlue = new RgbColor(COLOR_R_CLICKABLE_TEXT, COLOR_G_CLICKABLE_TEXT, COLOR_B_CLICKABLE_TEXT);
RgbColor colorRed = new RgbColor(255, 0, 0);
RgbColor colorWhite = new RgbColor(255, 253, 255);
RgbColor colorYellow = new RgbColor(255, 255, 0);
textFormClickable.setTextColor(colorYellow.asArgbInt());
textFormClickable.setTextSize(AttrHelper.fp2px(FP_TEXT_SIZE, context));
textFormClickable.setTextFont(Font.DEFAULT_BOLD);
textFormNormal.setTextSize(AttrHelper.fp2px(FP_TEXT_SIZE, context));
textFormNormal.setTextColor(colorWhite.asArgbInt());
// textFormNormal.setTextColor(ResourceTable.Color_grey_background);
}
... ...
/**
* Add default clickable style text to RichTextBuilder
*
* @param text text string
*/
public void addClickableText(String text) {
richTextBuilder.mergeForm(textFormClickable);
richTextBuilder.addText(text);
richTextBuilder.revertForm();
}
/**
* Add normal style text to RichTextBuilder
*
* @param text text string
*/
public void addNormalText(String text) {
richTextBuilder.mergeForm(textFormNormal);
richTextBuilder.addText(text);
richTextBuilder.revertForm();
}
Демонстрация обычного форматированного текста с использованием встроенного API:
RichText richText = new RichTextBuilder()
.mergeForm(new TextForm().setUnderline(true).setTextColor(colorWhite.asArgbInt())).addText("这是测试文本: ")
.revertForm().mergeForm(new TextForm().setSubscript(true).setTextColor(colorYellow.asArgbInt())).addText("#话题话题#")
.revertForm().mergeForm(new TextForm().setTextColor(colorWhite.asArgbInt())).addText("@某个人 ")
.revertForm().mergeForm(new TextForm().setTextColor(colorRed.asArgbInt())).addText("@22222 @kkkk")
.revertForm().addText("\n").mergeForm(new TextForm().setStrikethrough(true).setTextColor(colorWhite.asArgbInt())).addText("\n添加电话号码:186 0000 1111")
.build();
Демонстрация пользовательского форматирования текста: эффект клика, последовательное добавление текста:
//Добавление форматированного текста
RichTextFactory addRichTextFactory = new RichTextFactory(getContext());
addRichTextFactory.addNormalText("添加链接:");
addRichTextFactory.addClickableText("www.baidu.com");
addRichTextFactory.addNormalText(" 添加人物:");
addRichTextFactory.addClickableText("@22222 ");
addRichTextFactory.addNormalText("添加话题:");
addRichTextFactory.addClickableText("@啦啦啦啦啦");
RichText protocolPrivacyText = addRichTextFactory.getRichText();
DraweeTextView protocolPrivacyTextContainer = (DraweeTextView) findComponentById(ResourceTable.Id_protocolPrivacyText);
protocolPrivacyTextContainer.setRichText(protocolPrivacyText);
//Добавление эффекта клика
protocolPrivacyTextContainer.setClickedListener(new Component.ClickedListener() {
@Override
public void onClick(Component component) {
}
});
``` ```
Вставить текстовую эмодзи-картинку
PixelMapElement pixelMapElement = getPixelMapDrawable(MyMainAbilitySlice.this, ResourceTable.Media_e1);
DraweeSpan span = new DraweeSpan.Builder(
"https://i0.hdslb.com/bfs/vip/7a4cb0b644214d476ce198ddf6a7a0aa31311199.png").setLayout(WIDTH, HEIGHT)
.setPlaceHolderImage(pixelMapElement)
.build();
PixelMapElement pixelMapElement2 = getPixelMapDrawable(MyMainAbilitySlice.this, ResourceTable.Media_e2);
DraweeSpan span2 = new DraweeSpan.Builder(
"https://i0.hdslb.com/bfs/vip/7a4cb0b644214d476ce198ddf6a7a0aa31311199.png").setLayout(WIDTH, HEIGHT)
.setPlaceHolderImage(pixelMapElement2)
.build();
... ... DraweeTextView draweeTextView1 = new DraweeTextView(MyMainAbilitySlice.this); draweeTextView1.setText("O_O"); draweeTextView1.setTextSize(50); draweeTextView1.setAroundElements(span, null, span2, null); draweeTextView1.setTextColor(Color.WHITE); draweeTextView1.setPadding(8, 8, 8, 8);
## License
MIT License
Copyright (c) 2017 Shuyu Guo
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Вы можете оставить комментарий после Вход в систему
Неприемлемый контент может быть отображен здесь и не будет показан на странице. Вы можете проверить и изменить его с помощью соответствующей функции редактирования.
Если вы подтверждаете, что содержание не содержит непристойной лексики/перенаправления на рекламу/насилия/вульгарной порнографии/нарушений/пиратства/ложного/незначительного или незаконного контента, связанного с национальными законами и предписаниями, вы можете нажать «Отправить» для подачи апелляции, и мы обработаем ее как можно скорее.
Комментарии ( 0 )