file_path stringlengths 3 280 | file_language stringclasses 66 values | content stringlengths 1 1.04M | repo_name stringlengths 5 92 | repo_stars int64 0 154k | repo_description stringlengths 0 402 | repo_primary_language stringclasses 108 values | developer_username stringlengths 1 25 | developer_name stringlengths 0 30 | developer_company stringlengths 0 82 |
|---|---|---|---|---|---|---|---|---|---|
tests/Feature/PasswordConfirmationTest.php | PHP | <?php
namespace Tests\Feature;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class PasswordConfirmationTest extends TestCase
{
use RefreshDatabase;
public function test_confirm_password_screen_can_be_rendered(): void
{
$user = User::factory()->withPersonalTeam()->create();
$response = $this->actingAs($user)->get('/user/confirm-password');
$response->assertStatus(200);
}
public function test_password_can_be_confirmed(): void
{
$user = User::factory()->create();
$response = $this->actingAs($user)->post('/user/confirm-password', [
'password' => 'password',
]);
$response->assertRedirect();
$response->assertSessionHasNoErrors();
}
public function test_password_is_not_confirmed_with_invalid_password(): void
{
$user = User::factory()->create();
$response = $this->actingAs($user)->post('/user/confirm-password', [
'password' => 'wrong-password',
]);
$response->assertSessionHasErrors();
}
}
| yajra/yajrabox.com | 10 | Source code of yajrabox.com website. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
tests/Feature/PasswordResetTest.php | PHP | <?php
namespace Tests\Feature;
use App\Models\User;
use Illuminate\Auth\Notifications\ResetPassword;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Notification;
use Laravel\Fortify\Features;
use Tests\TestCase;
class PasswordResetTest extends TestCase
{
use RefreshDatabase;
public function test_reset_password_link_screen_can_be_rendered(): void
{
if (! Features::enabled(Features::resetPasswords())) {
$this->markTestSkipped('Password updates are not enabled.');
}
$response = $this->get('/forgot-password');
$response->assertStatus(200);
}
public function test_reset_password_link_can_be_requested(): void
{
if (! Features::enabled(Features::resetPasswords())) {
$this->markTestSkipped('Password updates are not enabled.');
}
Notification::fake();
$user = User::factory()->create();
$this->post('/forgot-password', [
'email' => $user->email,
]);
Notification::assertSentTo($user, ResetPassword::class);
}
public function test_reset_password_screen_can_be_rendered(): void
{
if (! Features::enabled(Features::resetPasswords())) {
$this->markTestSkipped('Password updates are not enabled.');
}
Notification::fake();
$user = User::factory()->create();
$this->post('/forgot-password', [
'email' => $user->email,
]);
Notification::assertSentTo($user, ResetPassword::class, function (object $notification) {
$response = $this->get('/reset-password/'.$notification->token);
$response->assertStatus(200);
return true;
});
}
public function test_password_can_be_reset_with_valid_token(): void
{
if (! Features::enabled(Features::resetPasswords())) {
$this->markTestSkipped('Password updates are not enabled.');
}
Notification::fake();
$user = User::factory()->create();
$this->post('/forgot-password', [
'email' => $user->email,
]);
Notification::assertSentTo($user, ResetPassword::class, function (object $notification) use ($user) {
$response = $this->post('/reset-password', [
'token' => $notification->token,
'email' => $user->email,
'password' => 'password',
'password_confirmation' => 'password',
]);
$response->assertSessionHasNoErrors();
return true;
});
}
}
| yajra/yajrabox.com | 10 | Source code of yajrabox.com website. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
tests/Feature/ProfileInformationTest.php | PHP | <?php
namespace Tests\Feature;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Jetstream\Http\Livewire\UpdateProfileInformationForm;
use Livewire\Livewire;
use Tests\TestCase;
class ProfileInformationTest extends TestCase
{
use RefreshDatabase;
public function test_current_profile_information_is_available(): void
{
$this->actingAs($user = User::factory()->create());
$component = Livewire::test(UpdateProfileInformationForm::class);
$this->assertEquals($user->name, $component->state['name']);
$this->assertEquals($user->email, $component->state['email']);
}
public function test_profile_information_can_be_updated(): void
{
$this->actingAs($user = User::factory()->create());
Livewire::test(UpdateProfileInformationForm::class)
->set('state', ['name' => 'Test Name', 'email' => 'test@example.com'])
->call('updateProfileInformation');
$this->assertEquals('Test Name', $user->fresh()->name);
$this->assertEquals('test@example.com', $user->fresh()->email);
}
}
| yajra/yajrabox.com | 10 | Source code of yajrabox.com website. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
tests/Feature/RegistrationTest.php | PHP | <?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Fortify\Features;
use Laravel\Jetstream\Jetstream;
use Tests\TestCase;
class RegistrationTest extends TestCase
{
use RefreshDatabase;
public function test_registration_screen_can_be_rendered(): void
{
if (! Features::enabled(Features::registration())) {
$this->markTestSkipped('Registration support is not enabled.');
}
$response = $this->get('/register');
$response->assertStatus(200);
}
public function test_registration_screen_cannot_be_rendered_if_support_is_disabled(): void
{
if (Features::enabled(Features::registration())) {
$this->markTestSkipped('Registration support is enabled.');
}
$response = $this->get('/register');
$response->assertStatus(404);
}
public function test_new_users_can_register(): void
{
if (! Features::enabled(Features::registration())) {
$this->markTestSkipped('Registration support is not enabled.');
}
$response = $this->post('/register', [
'name' => 'Test User',
'email' => 'test@example.com',
'password' => 'password',
'password_confirmation' => 'password',
'terms' => Jetstream::hasTermsAndPrivacyPolicyFeature(),
]);
$this->assertAuthenticated();
$response->assertRedirect(route('dashboard', absolute: false));
}
}
| yajra/yajrabox.com | 10 | Source code of yajrabox.com website. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
tests/Feature/TwoFactorAuthenticationSettingsTest.php | PHP | <?php
namespace Tests\Feature;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Fortify\Features;
use Laravel\Jetstream\Http\Livewire\TwoFactorAuthenticationForm;
use Livewire\Livewire;
use Tests\TestCase;
class TwoFactorAuthenticationSettingsTest extends TestCase
{
use RefreshDatabase;
public function test_two_factor_authentication_can_be_enabled(): void
{
if (! Features::canManageTwoFactorAuthentication()) {
$this->markTestSkipped('Two factor authentication is not enabled.');
}
$this->actingAs($user = User::factory()->create());
$this->withSession(['auth.password_confirmed_at' => time()]);
Livewire::test(TwoFactorAuthenticationForm::class)
->call('enableTwoFactorAuthentication');
$user = $user->fresh();
$this->assertNotNull($user->two_factor_secret);
$this->assertCount(8, $user->recoveryCodes());
}
public function test_recovery_codes_can_be_regenerated(): void
{
if (! Features::canManageTwoFactorAuthentication()) {
$this->markTestSkipped('Two factor authentication is not enabled.');
}
$this->actingAs($user = User::factory()->create());
$this->withSession(['auth.password_confirmed_at' => time()]);
$component = Livewire::test(TwoFactorAuthenticationForm::class)
->call('enableTwoFactorAuthentication')
->call('regenerateRecoveryCodes');
$user = $user->fresh();
$component->call('regenerateRecoveryCodes');
$this->assertCount(8, $user->recoveryCodes());
$this->assertCount(8, array_diff($user->recoveryCodes(), $user->fresh()->recoveryCodes()));
}
public function test_two_factor_authentication_can_be_disabled(): void
{
if (! Features::canManageTwoFactorAuthentication()) {
$this->markTestSkipped('Two factor authentication is not enabled.');
}
$this->actingAs($user = User::factory()->create());
$this->withSession(['auth.password_confirmed_at' => time()]);
$component = Livewire::test(TwoFactorAuthenticationForm::class)
->call('enableTwoFactorAuthentication');
$this->assertNotNull($user->fresh()->two_factor_secret);
$component->call('disableTwoFactorAuthentication');
$this->assertNull($user->fresh()->two_factor_secret);
}
}
| yajra/yajrabox.com | 10 | Source code of yajrabox.com website. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
tests/Feature/UpdatePasswordTest.php | PHP | <?php
namespace Tests\Feature;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Laravel\Jetstream\Http\Livewire\UpdatePasswordForm;
use Livewire\Livewire;
use Tests\TestCase;
class UpdatePasswordTest extends TestCase
{
use RefreshDatabase;
public function test_password_can_be_updated(): void
{
$this->actingAs($user = User::factory()->create());
Livewire::test(UpdatePasswordForm::class)
->set('state', [
'current_password' => 'password',
'password' => 'new-password',
'password_confirmation' => 'new-password',
])
->call('updatePassword');
$this->assertTrue(Hash::check('new-password', $user->fresh()->password));
}
public function test_current_password_must_be_correct(): void
{
$this->actingAs($user = User::factory()->create());
Livewire::test(UpdatePasswordForm::class)
->set('state', [
'current_password' => 'wrong-password',
'password' => 'new-password',
'password_confirmation' => 'new-password',
])
->call('updatePassword')
->assertHasErrors(['current_password']);
$this->assertTrue(Hash::check('password', $user->fresh()->password));
}
public function test_new_passwords_must_match(): void
{
$this->actingAs($user = User::factory()->create());
Livewire::test(UpdatePasswordForm::class)
->set('state', [
'current_password' => 'password',
'password' => 'new-password',
'password_confirmation' => 'wrong-password',
])
->call('updatePassword')
->assertHasErrors(['password']);
$this->assertTrue(Hash::check('password', $user->fresh()->password));
}
}
| yajra/yajrabox.com | 10 | Source code of yajrabox.com website. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
tests/TestCase.php | PHP | <?php
namespace Tests;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
{
//
}
| yajra/yajrabox.com | 10 | Source code of yajrabox.com website. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
tests/Unit/ExampleTest.php | PHP | <?php
namespace Tests\Unit;
use PHPUnit\Framework\TestCase;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*/
public function test_that_true_is_true(): void
{
$this->assertTrue(true);
}
}
| yajra/yajrabox.com | 10 | Source code of yajrabox.com website. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
vite.config.js | JavaScript | import { defineConfig } from 'vite';
import laravel, { refreshPaths } from 'laravel-vite-plugin';
import tailwindcss from "@tailwindcss/vite";
export default defineConfig({
plugins: [
laravel({
input: [
'resources/css/app.css',
'resources/js/app.js',
'resources/css/docs.css',
'resources/js/docs.js',
],
refresh: [
...refreshPaths,
'app/Http/Livewire/**',
],
}),
tailwindcss(),
],
});
| yajra/yajrabox.com | 10 | Source code of yajrabox.com website. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
SuperTextLib/build.gradle | Gradle | apply plugin: 'com.android.library'
android {
compileSdkVersion 27
buildToolsVersion "27.0.3"
defaultConfig {
minSdkVersion 17
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
consumerProguardFiles 'consumer-rules.pro'
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.0.0'
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
SuperTextLib/src/main/java/com/yc/supertextlib/AlignTextView.java | Java | package com.yc.supertextlib;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatTextView;
import android.text.Layout;
import android.text.StaticLayout;
import android.util.AttributeSet;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2019/07/18
* desc : 文本两端对齐
* revise: 建议使用BalanceTextView
* </pre>
*/
@Deprecated
public class AlignTextView extends AppCompatTextView {
/**
* 如何对齐
* 将一行剩余的宽度平分给当前单词的间距,这样来达到左右对齐的效果
*
* 实现原理:
* 通过StaticLayout来获取一行能展示多少的字符,然后计算剩余的宽度,进行绘制;
* 当绘制过程比较完美时,是由于计算的剩余宽度较小,看不出来效果;
*
* 缺点:
* 当存在单词较少时,会存在间隙过大的问题,比如第一行只有两个单词时,会出现间距过大的问题
*/
/**
* 是否只对齐一行
*/
private boolean alignOnlyOneLine;
public AlignTextView(Context context) {
this(context, null);
}
public AlignTextView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public AlignTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.AligningTextView);
alignOnlyOneLine = typedArray.getBoolean(R.styleable.AlignTextView_alignOnlyOneLine, false);
typedArray.recycle();
setTextColor(getCurrentTextColor());
}
@Override
public void setTextColor(int color) {
super.setTextColor(color);
getPaint().setColor(color);
}
@Override
protected void onDraw(Canvas canvas) {
//super.onDraw(canvas);
CharSequence content = getText();
if (!(content instanceof String)) {
super.onDraw(canvas);
return;
}
String text = (String) content;
Layout layout = getLayout();
for (int i = 0; i < layout.getLineCount(); ++i) {
int lineBaseline = layout.getLineBaseline(i) + getPaddingTop();
int lineStart = layout.getLineStart(i);
int lineEnd = layout.getLineEnd(i);
// 只有一行
if (alignOnlyOneLine && layout.getLineCount() == 1) {
String line = text.substring(lineStart, lineEnd);
float width = StaticLayout.getDesiredWidth(text, lineStart, lineEnd, getPaint());
this.drawScaledText(canvas, line, lineBaseline, width);
} else if (i == layout.getLineCount() - 1) {
// 最后一行
canvas.drawText(text.substring(lineStart), getPaddingLeft(), lineBaseline, getPaint());
break;
} else {
//中间行
String line = text.substring(lineStart, lineEnd);
float width = StaticLayout.getDesiredWidth(text, lineStart, lineEnd, getPaint());
this.drawScaledText(canvas, line, lineBaseline, width);
}
}
}
private void drawScaledText(Canvas canvas, String line, float baseLineY, float lineWidth) {
if (line.length() < 1) {
return;
}
float x = getPaddingLeft();
boolean forceNextLine = line.charAt(line.length() - 1) == 10;
int length = line.length() - 1;
if (forceNextLine || length == 0) {
canvas.drawText(line, x, baseLineY, getPaint());
return;
}
float d = (getMeasuredWidth() - lineWidth - getPaddingLeft() - getPaddingRight()) / length;
for (int i = 0; i < line.length(); ++i) {
String c = String.valueOf(line.charAt(i));
float cw = StaticLayout.getDesiredWidth(c, this.getPaint());
canvas.drawText(c, x, baseLineY, this.getPaint());
x += cw + d;
}
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
SuperTextLib/src/main/java/com/yc/supertextlib/AligningTextView.java | Java | package com.yc.supertextlib;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.support.v7.widget.AppCompatTextView;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.TextView;
import com.yc.supertextlib.R;
import java.util.ArrayList;
import java.util.List;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2019/07/18
* desc : 文本两端对齐
* revise: 建议使用BalanceTextView
* </pre>
*/
public class AligningTextView extends AppCompatTextView {
private float textHeight; // 单行文字高度
private float textLineSpaceExtra = 0; // 额外的行间距
private int width; // textView宽度
private List<String> lines = new ArrayList<String>(); // 分割后的行
private List<Integer> tailLines = new ArrayList<Integer>(); // 尾行
private Align align = Align.ALIGN_LEFT; // 默认最后一行左对齐
private boolean firstCalc = true; // 初始化计算
private float lineSpacingMultiplier = 1.0f;
private float lineSpacingAdd = 0.0f;
private int originalHeight = 0; //原始高度
private int originalLineCount = 0; //原始行数
private int originalPaddingBottom = 0; //原始paddingBottom
private boolean setPaddingFromMe = false;
// 尾行对齐方式
public enum Align {
ALIGN_LEFT, ALIGN_CENTER, ALIGN_RIGHT // 居中,居左,居右,针对段落最后一行
}
public AligningTextView(Context context) {
super(context);
setTextIsSelectable(false);
}
public AligningTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setTextIsSelectable(false);
int[] attributes = new int[]{android.R.attr.lineSpacingExtra, android.R.attr.lineSpacingMultiplier};
TypedArray arr = context.obtainStyledAttributes(attrs, attributes);
lineSpacingAdd = arr.getDimensionPixelSize(0, 0);
lineSpacingMultiplier = arr.getFloat(1, 1.0f);
originalPaddingBottom = getPaddingBottom();
arr.recycle();
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.AligningTextView);
int alignStyle = ta.getInt(R.styleable.AligningTextView_align, 0);
switch (alignStyle) {
case 1:
align = Align.ALIGN_CENTER;
break;
case 2:
align = Align.ALIGN_RIGHT;
break;
default:
align = Align.ALIGN_LEFT;
break;
}
ta.recycle();
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
//首先进行高度调整
if (firstCalc) {
width = getMeasuredWidth();
String text = getText().toString();
TextPaint paint = getPaint();
lines.clear();
tailLines.clear();
// 文本含有换行符时,分割单独处理
String[] items = text.split("\\n");
for (String item : items) {
calc(paint, item);
}
//使用替代textview计算原始高度与行数
measureTextViewHeight(text, paint.getTextSize(), getMeasuredWidth() -
getPaddingLeft() - getPaddingRight());
//获取行高
textHeight = 1.0f * originalHeight / originalLineCount;
textLineSpaceExtra = textHeight * (lineSpacingMultiplier - 1) + lineSpacingAdd;
//计算实际高度,加上多出的行的高度(一般是减少)
int heightGap = (int) ((textLineSpaceExtra + textHeight) * (lines.size() -
originalLineCount));
setPaddingFromMe = true;
//调整textview的paddingBottom来缩小底部空白
setPadding(getPaddingLeft(), getPaddingTop(), getPaddingRight(),
originalPaddingBottom + heightGap);
firstCalc = false;
}
}
@Override
protected void onDraw(Canvas canvas) {
TextPaint paint = getPaint();
paint.setColor(getCurrentTextColor());
paint.drawableState = getDrawableState();
width = getMeasuredWidth();
Paint.FontMetrics fm = paint.getFontMetrics();
float firstHeight = getTextSize() - (fm.bottom - fm.descent + fm.ascent - fm.top);
int gravity = getGravity();
if ((gravity & 0x1000) == 0) { // 是否垂直居中
firstHeight = firstHeight + (textHeight - firstHeight) / 2;
}
int paddingTop = getPaddingTop();
int paddingLeft = getPaddingLeft();
int paddingRight = getPaddingRight();
width = width - paddingLeft - paddingRight;
for (int i = 0; i < lines.size(); i++) {
float drawY = i * textHeight + firstHeight;
String line = lines.get(i);
// 绘画起始x坐标
float drawSpacingX = paddingLeft;
float gap = (width - paint.measureText(line));
float interval = gap / (line.length() - 1);
// 绘制最后一行
if (tailLines.contains(i)) {
interval = 0;
if (align == Align.ALIGN_CENTER) {
drawSpacingX += gap / 2;
} else if (align == Align.ALIGN_RIGHT) {
drawSpacingX += gap;
}
}
for (int j = 0; j < line.length(); j++) {
float drawX = paint.measureText(line.substring(0, j)) + interval * j;
canvas.drawText(line.substring(j, j + 1), drawX + drawSpacingX, drawY +
paddingTop + textLineSpaceExtra * i, paint);
}
}
}
/**
* 设置尾行对齐方式
*
* @param align 对齐方式
*/
public void setAlign(Align align) {
this.align = align;
invalidate();
}
/**
* 计算每行应显示的文本数
*
* @param text 要计算的文本
*/
private void calc(Paint paint, String text) {
if (text.length() == 0) {
lines.add("\n");
return;
}
int startPosition = 0; // 起始位置
float oneChineseWidth = paint.measureText("中");
int ignoreCalcLength = (int) (width / oneChineseWidth); // 忽略计算的长度
StringBuilder sb = new StringBuilder(text.substring(0, Math.min(ignoreCalcLength + 1, text.length())));
for (int i = ignoreCalcLength + 1; i < text.length(); i++) {
if (paint.measureText(text.substring(startPosition, i + 1)) > width) {
startPosition = i;
//将之前的字符串加入列表中
lines.add(sb.toString());
sb = new StringBuilder();
//添加开始忽略的字符串,长度不足的话直接结束,否则继续
if ((text.length() - startPosition) > ignoreCalcLength) {
sb.append(text.substring(startPosition, startPosition + ignoreCalcLength));
} else {
lines.add(text.substring(startPosition));
break;
}
i = i + ignoreCalcLength - 1;
} else {
sb.append(text.charAt(i));
}
}
if (sb.length() > 0) {
lines.add(sb.toString());
}
tailLines.add(lines.size() - 1);
}
@Override
public void setText(CharSequence text, BufferType type) {
firstCalc = true;
super.setText(text, type);
}
@Override
public void setPadding(int left, int top, int right, int bottom) {
if (!setPaddingFromMe) {
originalPaddingBottom = bottom;
}
setPaddingFromMe = false;
super.setPadding(left, top, right, bottom);
}
/**
* 获取文本实际所占高度,辅助用于计算行高,行数
*
* @param text 文本
* @param textSize 字体大小
* @param deviceWidth 屏幕宽度
*/
private void measureTextViewHeight(String text, float textSize, int deviceWidth) {
TextView textView = new TextView(getContext());
textView.setText(text);
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
int widthMeasureSpec = MeasureSpec.makeMeasureSpec(deviceWidth, MeasureSpec.EXACTLY);
int heightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
textView.measure(widthMeasureSpec, heightMeasureSpec);
originalLineCount = textView.getLineCount();
originalHeight = textView.getMeasuredHeight();
}
} | yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
SuperTextLib/src/main/java/com/yc/supertextlib/BalanceTextView.java | Java | package com.yc.supertextlib;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Canvas;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatTextView;
import android.text.Layout;
import android.text.Spanned;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2019/07/18
* desc : 文本两端对齐
* revise:
* </pre>
*/
public class BalanceTextView extends AppCompatTextView {
private static final String TAG = BalanceTextView.class.getSimpleName();
/**
* 起始位置
*/
private static final int GRAVITY_START = 1001;
/**
* 结尾位置
*/
private static final int GRAVITY_END = 1002;
/**
* 中间位置
*/
private static final int GRAVITY_CENTER = 1003;
/**
* 绘制文字的起始Y坐标
*/
private float mLineY;
/**
* 文字的宽度
*/
private int mViewWidth;
/**
* 段落间距
*/
private int paragraphSpacing = TextViewUtils.dipToPx(getContext(), 15);
/**
* 行间距
*/
private int lineSpacing = TextViewUtils.dipToPx(getContext(), 2);
/**
* 当前所有行数的集合
*/
private ArrayList<List<List<String>>> mParagraphLineList;
/**
* 当前所有的行数
*/
private int mLineCount;
/**
* 每一段单词的内容集合
*/
private ArrayList<List<String>> mParagraphWordList;
/**
* 空格字符
*/
private static final String BLANK = " ";
/**
* 英语单词元音字母
*/
private String[] vowel = {"a", "e", "i", "o", "u"};
/**
* 英语单词元音字母集合
*/
private List<String> vowels = Arrays.asList(vowel);
/**
* 当前测量的间距
*/
private int measuredWidth;
/**
* 左padding
*/
private int paddingStart;
/**
* 右padding
*/
private int paddingEnd;
/**
* 顶padding
*/
private int paddingTop;
/**
* 底padding
*/
private int paddingBottom;
/**
* 布局的方向
*/
private int textGravity;
public BalanceTextView(Context context) {
this(context,null);
}
public BalanceTextView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs,0);
}
public BalanceTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (isSpan()) {
return;
}
mParagraphLineList = null;
mParagraphWordList = null;
mLineY = 0;
//获取测量的宽度
measuredWidth = getMeasuredWidth();
//获取上下左右的padding值
paddingStart = getPaddingStart();
paddingEnd = getPaddingEnd();
paddingTop = getPaddingTop();
paddingBottom = getPaddingBottom();
//这个是view的宽度 = 测量宽度 - 左间距 - 右间距
mViewWidth = measuredWidth - paddingStart - paddingEnd;
getParagraphList();
for (List<String> frontList : mParagraphWordList) {
mParagraphLineList.add(getLineList(frontList));
}
Log.i(TAG, "onMeasure----------");
setMeasuredDimension(measuredWidth,
(mParagraphLineList.size() - 1) * paragraphSpacing
+ mLineCount * (getLineHeight() + lineSpacing) + paddingTop + paddingBottom);
}
@Override
protected void onDraw(Canvas canvas) {
if (isSpan()) {
super.onDraw(canvas);
return;
}
Log.i(TAG, "onDraw----------");
TextPaint paint = getPaint();
paint.setColor(getCurrentTextColor());
paint.drawableState = getDrawableState();
mLineY = 0;
float textSize = getTextSize();
mLineY += textSize + paddingTop;
Layout layout = getLayout();
if (layout == null) {
return;
}
textGravity = getTextGravity();
adjust(canvas, paint);
}
/**
* 计算每一段绘制的内容
* @param frontList
* @return
*/
private synchronized List<List<String>> getLineList(List<String> frontList) {
Log.i(TAG, "getLineList-----");
StringBuilder sb = new StringBuilder();
List<List<String>> lineLists = new ArrayList<>();
List<String> lineList = new ArrayList<>();
float width = 0;
String temp = "";
String front = "";
for (int i = 0; i < frontList.size(); i++) {
front = frontList.get(i);
if (!TextUtils.isEmpty(temp)) {
sb.append(temp);
lineList.add(temp);
if (!TextViewUtils.isCN(temp)) {
sb.append(BLANK);
}
temp = "";
}
if (TextViewUtils.isCN(front)) {
sb.append(front);
} else {
if ((i + 1) < frontList.size()) {
String nextFront = frontList.get(i + 1);
if (TextViewUtils.isCN(nextFront)) {
sb.append(front);
} else {
sb.append(front).append(BLANK);
}
} else {
sb.append(front);
}
}
lineList.add(front);
width = StaticLayout.getDesiredWidth(sb.toString(), getPaint());
if (width > mViewWidth) {
// 先判断最后一个单词是否是英文的,是的话则切割,否则的话就移除最后一个
int lastIndex = lineList.size() - 1;
String lastWord = lineList.get(lastIndex);
String lastTemp = "";
lineList.remove(lastIndex);
if (TextViewUtils.isCN(lastWord)) {
addLines(lineLists, lineList);
lastTemp = lastWord;
} else {
// 否则的话则截取字符串
String substring = sb.substring(0, sb.length() - lastWord.length() - 1);
sb.delete(0, sb.toString().length());
sb.append(substring).append(BLANK);
String tempLastWord = "";
int length = lastWord.length();
if (length <= 3) {
addLines(lineLists, lineList);
lastTemp = lastWord;
} else {
int cutoffIndex = 0;
for (int j = 0; j < length; j++) {
tempLastWord = String.valueOf(lastWord.charAt(j));
sb.append(tempLastWord);
if (vowels.contains(tempLastWord)) {
// 根据元音字母来进行截断
if (j + 1 < length) {
String nextTempLastWord = String.valueOf(lastWord.charAt(j + 1));
sb.append(nextTempLastWord);
width = StaticLayout.getDesiredWidth(sb.toString(), getPaint());
cutoffIndex = j;
if (width > mViewWidth) {
if (j > 2 && j <= length - 2) {
// 单词截断后,前面的字符小于2个时,则不进行截断
String lastFinalWord = lastWord.substring(0, cutoffIndex + 2) + "-";
lineList.add(lastFinalWord);
addLines(lineLists, lineList);
lastTemp = lastWord.substring(cutoffIndex + 2, length);
} else {
addLines(lineLists, lineList);
lastTemp = lastWord;
}
break;
}
} else {
addLines(lineLists, lineList);
lastTemp = lastWord;
break;
}
}
width = StaticLayout.getDesiredWidth(sb.toString(), getPaint());
// 找不到元音,则走默认的逻辑
if (width > mViewWidth) {
if (j > 2 && j <= length - 2) {
// 单词截断后,前面的字符小于2个时,则不进行截断
String lastFinalWord = lastWord.substring(0, j) + "-";
lineList.add(lastFinalWord);
addLines(lineLists, lineList);
lastTemp = lastWord.substring(j, length);
} else {
addLines(lineLists, lineList);
lastTemp = lastWord;
}
break;
}
}
}
}
sb.delete(0, sb.toString().length());
temp = lastTemp;
}
if (lineList.size() > 0 && i == frontList.size() - 1) {
addLines(lineLists, lineList);
}
}
if (!TextUtils.isEmpty(temp)) {
lineList.add(temp);
addLines(lineLists, lineList);
}
mLineCount += lineLists.size();
return lineLists;
}
/**
* 添加一行到单词内容
*
* @param lineLists 总单词集合
* @param lineList 当前要添加的集合
*/
private void addLines(List<List<String>> lineLists, List<String> lineList) {
if (lineLists == null || lineList == null) {
return;
}
List<String> tempLines = new ArrayList<>(lineList);
lineLists.add(tempLines);
lineList.clear();
}
/**
* 获取段落
*/
private void getParagraphList() {
CharSequence charSequence = getText();
if (TextUtils.isEmpty(charSequence)) {
return;
}
String text = charSequence.toString()
.replaceAll(" ", "")
.replaceAll(" ", "")
.replaceAll("\\r", "").trim();
mLineCount = 0;
String[] items = text.split("\\n");
mParagraphLineList = new ArrayList<>();
mParagraphWordList = new ArrayList<>();
for (String item : items) {
if (item.length() != 0) {
mParagraphWordList.add(getWordList(item));
}
}
}
/**
* 截取每一段内容的每一个单词
*
* @param text
* @return
*/
private synchronized List<String> getWordList(String text) {
if (TextUtils.isEmpty(text)) {
return new ArrayList<>();
}
Log.i(TAG, "getWordList ");
List<String> frontList = new ArrayList<>();
StringBuilder str = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
String charAt = String.valueOf(text.charAt(i));
if (!BLANK.equals(charAt)) {
if (TextViewUtils.checkIsSymbol(charAt)) {
boolean isEmptyStr = str.length() == 0;
str.append(charAt);
if (!isEmptyStr) {
// 中英文都需要将字符串添加到这里;
frontList.add(str.toString());
str.delete(0, str.length());
}
} else {
if (TextViewUtils.isCN(str.toString())){
frontList.add(str.toString());
str.delete(0, str.length());
}
str.append(charAt);
}
} else {
if (!TextUtils.isEmpty(str.toString())) {
frontList.add(str.toString().replaceAll(BLANK, ""));
str.delete(0, str.length());
}
}
}
if (str.length() != 0) {
frontList.add(str.toString());
str.delete(0, str.length());
}
return frontList;
}
/**
* 中英文排版效果
*
* @param canvas
*/
private synchronized void adjust(Canvas canvas, TextPaint paint) {
int size = mParagraphWordList.size();
for (int j = 0; j < size; j++) {
// 遍历每一段
List<List<String>> lineList = mParagraphLineList.get(j);
for (int i = 0; i < lineList.size(); i++) {
// 遍历每一段的每一行
List<String> lineWords = lineList.get(i);
if (i == lineList.size() - 1) {
drawScaledEndText(canvas, lineWords, paint);
} else {
drawScaledText(canvas, lineWords, paint);
}
mLineY += (getLineHeight() + lineSpacing);
}
mLineY += paragraphSpacing;
}
}
/**
* 绘制最后一行文字
* @param canvas
* @param lineWords
* @param paint
*/
private void drawScaledEndText(Canvas canvas, List<String> lineWords, TextPaint paint) {
if (canvas == null || lineWords == null || paint == null) {
return;
}
StringBuilder sb = new StringBuilder();
for (String aSplit : lineWords) {
if (TextViewUtils.isCN(aSplit)) {
sb.append(aSplit);
} else {
sb.append(aSplit).append(BLANK);
}
}
/**
* 最后一行适配布局方向
* android:gravity=""
* android:textAlignment=""
* 默认不设置则为左边
* 如果同时设置gravity和textAlignment属性,则以textAlignment的属性为准
* 也就是说textAlignment的属性优先级大于gravity的属性
*/
if (GRAVITY_START == textGravity) {
canvas.drawText(sb.toString(), paddingStart, mLineY, paint);
} else if (GRAVITY_END == textGravity) {
float width = StaticLayout.getDesiredWidth(sb.toString(), getPaint());
canvas.drawText(sb.toString(), measuredWidth - width - paddingStart, mLineY, paint);
} else {
float width = StaticLayout.getDesiredWidth(sb.toString(), getPaint());
canvas.drawText(sb.toString(), (mViewWidth - width) / 2, mLineY, paint);
}
}
/**
* 获取布局的方向
*/
private int getTextGravity() {
final int layoutDirection = getLayoutDirection();
final int absoluteGravity = Gravity.getAbsoluteGravity(getGravity(), layoutDirection);
int lastGravity = absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK;
int textAlignment = getTextAlignment();
if (TEXT_ALIGNMENT_TEXT_START == textAlignment
|| TEXT_ALIGNMENT_VIEW_START == textAlignment
|| Gravity.LEFT == lastGravity) {
return GRAVITY_START;
} else if (TEXT_ALIGNMENT_TEXT_END == textAlignment
|| TEXT_ALIGNMENT_VIEW_END == textAlignment
|| Gravity.RIGHT == lastGravity) {
return GRAVITY_END;
} else {
return GRAVITY_CENTER;
}
}
/**
* 绘制左右对齐效果
*
* @param canvas
* @param line
* @param paint
*/
private void drawScaledText(Canvas canvas, List<String> line, TextPaint paint) {
if (canvas == null || line == null || paint == null) {
return;
}
StringBuilder sb = new StringBuilder();
for (String aSplit : line) {
sb.append(aSplit);
}
float lineWidth = StaticLayout.getDesiredWidth(sb, getPaint());
float cw = 0;
if (GRAVITY_START == textGravity) {
cw = paddingStart;
} else if (GRAVITY_END == textGravity){
cw = paddingEnd;
} else {
cw = paddingStart;
}
float d = (mViewWidth - lineWidth) / (line.size() - 1);
for (String aSplit : line) {
canvas.drawText(aSplit, cw, mLineY, getPaint());
cw += StaticLayout.getDesiredWidth(aSplit + "", paint) + d;
}
}
/**
* 判断是否是富文本
*/
public boolean isSpan() {
CharSequence charSequence = getText();
return charSequence instanceof Spanned;
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
SuperTextLib/src/main/java/com/yc/supertextlib/TextViewUtils.java | Java | package com.yc.supertextlib;
import android.content.ClipboardManager;
import android.content.Context;
import android.util.Log;
import java.io.UnsupportedEncodingException;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2019/07/18
* desc : 文本两端对齐的utils
* revise:
* </pre>
*/
public final class TextViewUtils {
/**
* 功能:判断字符串是否有中文
* @param str 字符串
* @return
*/
public static boolean isCN(String str) {
try {
byte[] bytes = str.getBytes("UTF-8");
if (bytes.length == str.length()) {
return false;
} else {
return true;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return false;
}
/**
* 复制文本到剪切板
* @param text 文本
*/
public static void copy(Context context, String text) {
if (context == null){
return;
}
ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
try {
android.content.ClipData clip = android.content.ClipData.newPlainText(null, text);
if (clipboard != null) {
clipboard.setPrimaryClip(clip);
}
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 判断是否包含标点符号等内容
* @param s 字符串
* @return
*/
public static boolean checkIsSymbol(String s) {
boolean b = false;
String tmp = s;
tmp = tmp.replaceAll("\\p{P}", "");
if (s.length() != tmp.length()) {
b = true;
}
return b;
}
/**
* dp转为px
* @param var0 上下文
* @param var1 值
* @return
*/
public static int dipToPx(Context var0, float var1) {
float var2 = var0.getResources().getDisplayMetrics().density;
return (int) (var1 * var2 + 0.5F);
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
YCCustomTextLib/build.gradle | Gradle | apply plugin: 'com.android.library'
android {
compileSdkVersion 27
buildToolsVersion "27.0.3"
defaultConfig {
minSdkVersion 16
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.0.0'
}
/** 以下开始是将Android Library上传到jcenter的相关配置**/
apply plugin: 'com.github.dcendents.android-maven'
apply plugin: 'com.jfrog.bintray'
//项目主页
def siteUrl = 'https://github.com/yangchong211/YCCustomText' // project homepage
//项目的版本控制地址
def gitUrl = 'https://github.com/yangchong211/YCCustomText.git' // project git
//发布到组织名称名字,必须填写
group = "cn.yc"
//发布到JCenter上的项目名字,必须填写
def libName = "YCCustomTextLib"
// 版本号,下次更新是只需要更改版本号即可
version = "2.1.5"
/** 上面配置后上传至jcenter后的编译路径是这样的: compile 'cn.yc:YCCustomTextLib:1.0' **/
//生成源文件
task sourcesJar(type: Jar) {
from android.sourceSets.main.java.srcDirs
classifier = 'sources'
}
//生成文档
task javadoc(type: Javadoc) {
source = android.sourceSets.main.java.srcDirs
classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
options.encoding "UTF-8"
options.charSet 'UTF-8'
options.author true
options.version true
options.links "https://github.com/linglongxin24/FastDev/tree/master/mylibrary/docs/javadoc"
failOnError false
}
//文档打包成jar
task javadocJar(type: Jar, dependsOn: javadoc) {
classifier = 'javadoc'
from javadoc.destinationDir
}
//拷贝javadoc文件
task copyDoc(type: Copy) {
from "${buildDir}/docs/"
into "docs"
}
//上传到jcenter所需要的源码文件
artifacts {
archives javadocJar
archives sourcesJar
}
// 配置maven库,生成POM.xml文件
install {
repositories.mavenInstaller {
// This generates POM.xml with proper parameters
pom {
project {
packaging 'aar'
//项目描述,自由填写
name 'This is a custom text'
url siteUrl
licenses {
license {
//开源协议
name 'The Apache Software License, Version 2.0'
url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
}
}
developers {
developer {
//开发者的个人信息,根据个人信息填写
id 'yangchong'
name 'yc'
email 'yangchong211@163.com'
}
}
scm {
connection gitUrl
developerConnection gitUrl
url siteUrl
}
}
}
}
}
//上传到jcenter
Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream())
bintray {
user = properties.getProperty("bintray.user") //读取 local.properties 文件里面的 bintray.user
key = properties.getProperty("bintray.apikey") //读取 local.properties 文件里面的 bintray.apikey
configurations = ['archives']
pkg {
repo = "maven"
name = libName //发布到JCenter上的项目名字,必须填写
desc = 'Android Custom Text' //项目描述
websiteUrl = siteUrl
vcsUrl = gitUrl
licenses = ["Apache-2.0"]
publish = true
}
}
javadoc {
options {
//如果你的项目里面有中文注释的话,必须将格式设置为UTF-8,不然会出现乱码
encoding "UTF-8"
charSet 'UTF-8'
author true
version true
links "http://docs.oracle.com/javase/7/docs/api"
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
YCCustomTextLib/src/main/assets/editor.html | HTML |
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="user-scalable=no">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="normalize.css">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="editor" contenteditable="true"></div>
<script type="text/javascript" src="rich_editor.js"></script>
</body>
</html>
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
YCCustomTextLib/src/main/assets/normalize.css | CSS |
html {
font-family: sans-serif; /* 1 */
-webkit-text-size-adjust: 100%; /* 2 */
}
/**
* Remove default margin.
*/
body {
margin: 0;
}
/* HTML5 display definitions
========================================================================== */
/**
* Correct `block` display not defined for any HTML5 element in IE 8/9.
* Correct `block` display not defined for `details` or `summary` in IE 10/11
* and Firefox.
* Correct `block` display not defined for `main` in IE 11.
*/
article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
main,
menu,
nav,
section,
summary {
display: block;
}
/**
* 1. Correct `inline-block` display not defined in IE 8/9.
* 2. Normalize vertical alignment of `progress` in Chrome, Firefox, and Opera.
*/
audio,
canvas,
progress,
video {
display: inline-block; /* 1 */
vertical-align: baseline; /* 2 */
}
/**
* Prevent modern browsers from displaying `audio` without controls.
* Remove excess height in iOS 5 devices.
*/
audio:not([controls]) {
display: none;
height: 0;
}
/**
* Address `[hidden]` styling not present in IE 8/9/10.
* Hide the `template` element in IE 8/9/11, Safari, and Firefox < 22.
*/
[hidden],
template {
display: none;
}
/* Links
========================================================================== */
/**
* Remove the gray background color from active links in IE 10.
*/
a {
background-color: transparent;
}
/**
* Improve readability when focused and also mouse hovered in all browsers.
*/
a:active,
a:hover {
outline: 0;
}
/* Text-level semantics
========================================================================== */
/**
* Address styling not present in IE 8/9/10/11, Safari, and Chrome.
*/
abbr[title] {
border-bottom: 1px dotted;
}
/**
* Address style set to `bolder` in Firefox 4+, Safari, and Chrome.
*/
b,
strong {
font-weight: bold;
}
/**
* Address styling not present in Safari and Chrome.
*/
dfn {
font-style: italic;
}
/**
* Address variable `h1` font-size and margin within `section` and `article`
* contexts in Firefox 4+, Safari, and Chrome.
*/
h1 {
font-size: 2em;
margin: 0.67em 0;
}
/**
* Address styling not present in IE 8/9.
*/
mark {
background: #ff0;
color: #000;
}
/**
* Address inconsistent and variable font size in all browsers.
*/
small {
font-size: 80%;
}
/**
* Prevent `sub` and `sup` affecting `line-height` in all browsers.
*/
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sup {
top: -0.5em;
}
sub {
bottom: -0.25em;
}
/* Embedded content
========================================================================== */
/**
* Remove border when inside `a` element in IE 8/9/10.
*/
img {
border: 0;
}
/**
* Correct overflow not hidden in IE 9/10/11.
*/
svg:not(:root) {
overflow: hidden;
}
/* Grouping content
========================================================================== */
/**
* Address margin not present in IE 8/9 and Safari.
*/
figure {
margin: 1em 40px;
}
/**
* Address differences between Firefox and other browsers.
*/
hr {
box-sizing: content-box;
height: 0;
}
/**
* Contain overflow in all browsers.
*/
pre {
overflow: auto;
}
/**
* Address odd `em`-unit font size rendering in all browsers.
*/
code,
kbd,
pre,
samp {
font-family: monospace, monospace;
font-size: 1em;
}
/* Forms
========================================================================== */
/**
* Known limitation: by default, Chrome and Safari on OS X allow very limited
* styling of `select`, unless a `border` property is set.
*/
/**
* 1. Correct color not being inherited.
* Known issue: affects color of disabled elements.
* 2. Correct font properties not being inherited.
* 3. Address margins set differently in Firefox 4+, Safari, and Chrome.
*/
button,
input,
optgroup,
select,
textarea {
color: inherit; /* 1 */
font: inherit; /* 2 */
margin: 0; /* 3 */
}
/**
* Address `overflow` set to `hidden` in IE 8/9/10/11.
*/
button {
overflow: visible;
}
/**
* Address inconsistent `text-transform` inheritance for `button` and `select`.
* All other form control elements do not inherit `text-transform` values.
* Correct `button` style inheritance in Firefox, IE 8/9/10/11, and Opera.
* Correct `select` style inheritance in Firefox.
*/
button,
select {
text-transform: none;
}
/**
* 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio`
* and `video` controls.
* 2. Correct inability to style clickable `input` types in iOS.
* 3. Improve usability and consistency of cursor style between image-type
* `input` and others.
*/
button,
html input[type="button"], /* 1 */
input[type="reset"],
input[type="submit"] {
-webkit-appearance: button; /* 2 */
cursor: pointer; /* 3 */
}
/**
* Re-set default cursor for disabled elements.
*/
button[disabled],
html input[disabled] {
cursor: default;
}
/**
* Address Firefox 4+ setting `line-height` on `input` using `!important` in
* the UA stylesheet.
*/
input {
line-height: normal;
}
/**
* It's recommended that you don't attempt to style these elements.
* Firefox's implementation doesn't respect box-sizing, padding, or width.
*
* 1. Address box sizing set to `content-box` in IE 8/9/10.
* 2. Remove excess padding in IE 8/9/10.
*/
input[type="checkbox"],
input[type="radio"] {
box-sizing: border-box; /* 1 */
padding: 0; /* 2 */
}
/**
* Fix the cursor style for Chrome's increment/decrement buttons. For certain
* `font-size` values of the `input`, it causes the cursor style of the
* decrement button to change from `default` to `text`.
*/
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
height: auto;
}
/**
* 1. Address `appearance` set to `searchfield` in Safari and Chrome.
* 2. Address `box-sizing` set to `border-box` in Safari and Chrome
*/
input[type="search"] {
-webkit-appearance: textfield; /* 1 */
-webkit-box-sizing: content-box; /* 2 */
box-sizing: content-box;
}
/**
* Remove inner padding and search cancel button in Safari and Chrome on OS X.
* Safari (but not Chrome) clips the cancel button when the search input has
* padding (and `textfield` appearance).
*/
input[type="search"]::-webkit-search-cancel-button,
input[type="search"]::-webkit-search-decoration {
-webkit-appearance: none;
}
/**
* Define consistent border, margin, and padding.
*/
fieldset {
border: 1px solid #c0c0c0;
margin: 0 2px;
padding: 0.35em 0.625em 0.75em;
}
/**
* 1. Correct `color` not being inherited in IE 8/9/10/11.
* 2. Remove padding so people aren't caught out if they zero out fieldsets.
*/
legend {
border: 0; /* 1 */
padding: 0; /* 2 */
}
/**
* Remove default vertical scrollbar in IE 8/9/10/11.
*/
textarea {
overflow: auto;
}
/**
* Don't inherit the `font-weight` (applied by a rule above).
* NOTE: the default cannot safely be changed in Chrome and Safari on OS X.
*/
optgroup {
font-weight: bold;
}
/* Tables
========================================================================== */
/**
* Remove most spacing between table cells.
*/
table {
border-collapse: collapse;
border-spacing: 0;
}
td,
th {
padding: 0;
} | yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
YCCustomTextLib/src/main/assets/rich_editor.js | JavaScript |
var RE = {};
RE.currentSelection = {
"startContainer": 0,
"startOffset": 0,
"endContainer": 0,
"endOffset": 0};
RE.editor = document.getElementById('editor');
document.addEventListener("selectionchange", function() { RE.backuprange(); });
// Initializations
RE.callback = function() {
window.location.href = "re-callback://" + encodeURI(RE.getHtml());
}
RE.setHtml = function(contents) {
RE.editor.innerHTML = decodeURIComponent(contents.replace(/\+/g, '%20'));
}
RE.getHtml = function() {
return RE.editor.innerHTML;
}
RE.getText = function() {
return RE.editor.innerText;
}
RE.setBaseTextColor = function(color) {
RE.editor.style.color = color;
}
RE.setBaseFontSize = function(size) {
RE.editor.style.fontSize = size;
}
RE.setPadding = function(left, top, right, bottom) {
RE.editor.style.paddingLeft = left;
RE.editor.style.paddingTop = top;
RE.editor.style.paddingRight = right;
RE.editor.style.paddingBottom = bottom;
}
RE.setBackgroundColor = function(color) {
document.body.style.backgroundColor = color;
}
RE.setBackgroundImage = function(image) {
RE.editor.style.backgroundImage = image;
}
RE.setWidth = function(size) {
RE.editor.style.minWidth = size;
}
RE.setHeight = function(size) {
RE.editor.style.height = size;
}
RE.setTextAlign = function(align) {
RE.editor.style.textAlign = align;
}
RE.setVerticalAlign = function(align) {
RE.editor.style.verticalAlign = align;
}
RE.setPlaceholder = function(placeholder) {
RE.editor.setAttribute("placeholder", placeholder);
}
RE.setInputEnabled = function(inputEnabled) {
RE.editor.contentEditable = String(inputEnabled);
}
RE.undo = function() {
document.execCommand('undo', false, null);
}
RE.redo = function() {
document.execCommand('redo', false, null);
}
RE.setBold = function() {
document.execCommand('bold', false, null);
}
RE.setItalic = function() {
document.execCommand('italic', false, null);
}
RE.setSubscript = function() {
document.execCommand('subscript', false, null);
}
RE.setSuperscript = function() {
document.execCommand('superscript', false, null);
}
RE.setStrikeThrough = function() {
document.execCommand('strikeThrough', false, null);
}
RE.setUnderline = function() {
document.execCommand('underline', false, null);
}
RE.setBullets = function() {
document.execCommand('insertUnorderedList', false, null);
}
RE.setNumbers = function() {
document.execCommand('insertOrderedList', false, null);
}
RE.setTextColor = function(color) {
RE.restorerange();
document.execCommand("styleWithCSS", null, true);
document.execCommand('foreColor', false, color);
document.execCommand("styleWithCSS", null, false);
}
RE.setTextBackgroundColor = function(color) {
RE.restorerange();
document.execCommand("styleWithCSS", null, true);
document.execCommand('hiliteColor', false, color);
document.execCommand("styleWithCSS", null, false);
}
RE.setFontSize = function(fontSize){
document.execCommand("fontSize", false, fontSize);
}
RE.setHeading = function(heading) {
document.execCommand('formatBlock', false, '<h'+heading+'>');
}
RE.setIndent = function() {
document.execCommand('indent', false, null);
}
RE.setOutdent = function() {
document.execCommand('outdent', false, null);
}
RE.setJustifyLeft = function() {
document.execCommand('justifyLeft', false, null);
}
RE.setJustifyCenter = function() {
document.execCommand('justifyCenter', false, null);
}
RE.setJustifyRight = function() {
document.execCommand('justifyRight', false, null);
}
RE.setBlockquote = function() {
document.execCommand('formatBlock', false, '<blockquote>');
}
RE.insertImage = function(url, alt) {
var html = '<img src="' + url + '" alt="' + alt + '" />';
RE.insertHTML(html);
}
RE.insertHTML = function(html) {
RE.restorerange();
document.execCommand('insertHTML', false, html);
}
RE.insertLink = function(url, title) {
RE.restorerange();
var sel = document.getSelection();
if (sel.toString().length == 0) {
document.execCommand("insertHTML",false,"<a href='"+url+"'>"+title+"</a>");
} else if (sel.rangeCount) {
var el = document.createElement("a");
el.setAttribute("href", url);
el.setAttribute("title", title);
var range = sel.getRangeAt(0).cloneRange();
range.surroundContents(el);
sel.removeAllRanges();
sel.addRange(range);
}
RE.callback();
}
RE.setTodo = function(text) {
var html = '<input type="checkbox" name="'+ text +'" value="'+ text +'"/> ';
document.execCommand('insertHTML', false, html);
}
RE.prepareInsert = function() {
RE.backuprange();
}
RE.backuprange = function(){
var selection = window.getSelection();
if (selection.rangeCount > 0) {
var range = selection.getRangeAt(0);
RE.currentSelection = {
"startContainer": range.startContainer,
"startOffset": range.startOffset,
"endContainer": range.endContainer,
"endOffset": range.endOffset};
}
}
RE.restorerange = function(){
var selection = window.getSelection();
selection.removeAllRanges();
var range = document.createRange();
range.setStart(RE.currentSelection.startContainer, RE.currentSelection.startOffset);
range.setEnd(RE.currentSelection.endContainer, RE.currentSelection.endOffset);
selection.addRange(range);
}
RE.enabledEditingItems = function(e) {
var items = [];
if (document.queryCommandState('bold')) {
items.push('bold');
}
if (document.queryCommandState('italic')) {
items.push('italic');
}
if (document.queryCommandState('subscript')) {
items.push('subscript');
}
if (document.queryCommandState('superscript')) {
items.push('superscript');
}
if (document.queryCommandState('strikeThrough')) {
items.push('strikeThrough');
}
if (document.queryCommandState('underline')) {
items.push('underline');
}
if (document.queryCommandState('insertOrderedList')) {
items.push('orderedList');
}
if (document.queryCommandState('insertUnorderedList')) {
items.push('unorderedList');
}
if (document.queryCommandState('justifyCenter')) {
items.push('justifyCenter');
}
if (document.queryCommandState('justifyFull')) {
items.push('justifyFull');
}
if (document.queryCommandState('justifyLeft')) {
items.push('justifyLeft');
}
if (document.queryCommandState('justifyRight')) {
items.push('justifyRight');
}
if (document.queryCommandState('insertHorizontalRule')) {
items.push('horizontalRule');
}
var formatBlock = document.queryCommandValue('formatBlock');
if (formatBlock.length > 0) {
items.push(formatBlock);
}
window.location.href = "re-state://" + encodeURI(items.join(','));
}
RE.focus = function() {
var range = document.createRange();
range.selectNodeContents(RE.editor);
range.collapse(false);
var selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
RE.editor.focus();
}
RE.blurFocus = function() {
RE.editor.blur();
}
RE.removeFormat = function() {
document.execCommand('removeFormat', false, null);
}
// Event Listeners
RE.editor.addEventListener("input", RE.callback);
RE.editor.addEventListener("keyup", function(e) {
var KEY_LEFT = 37, KEY_RIGHT = 39;
if (e.which == KEY_LEFT || e.which == KEY_RIGHT) {
RE.enabledEditingItems(e);
}
});
RE.editor.addEventListener("click", RE.enabledEditingItems);
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
YCCustomTextLib/src/main/assets/style.css | CSS |
@charset "UTF-8";
html {
height: 100%;
}
body {
overflow: scroll;
display: table;
table-layout: fixed;
width: 100%;
min-height:100%;
}
#editor {
display: table-cell;
outline: 0px solid transparent;
background-repeat: no-repeat;
background-position: center;
background-size: cover;
}
#editor[placeholder]:empty:not(:focus):before {
content: attr(placeholder);
opacity: .5;
}}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
YCCustomTextLib/src/main/java/com/ns/yc/yccustomtextlib/edit/inter/ImageLoader.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
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.
*/
package com.ns.yc.yccustomtextlib.edit.inter;
import com.ns.yc.yccustomtextlib.edit.view.HyperImageView;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2018/3/31
* desc : 接口
* revise: 暴露给开发者自定义设置图片
* </pre>
*/
public interface ImageLoader {
/**
* 加载图片
* @param imagePath 图片地址
* @param imageView view
* @param imageHeight 图片高度
*/
void loadImage(String imagePath, HyperImageView imageView, int imageHeight);
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
YCCustomTextLib/src/main/java/com/ns/yc/yccustomtextlib/edit/inter/OnHyperChangeListener.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
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.
*/
package com.ns.yc.yccustomtextlib.edit.inter;
import android.view.View;
/**
* <pre>
* @author yangchong
* blog : https://github.com/yangchong211/YCStatusBar
* time : 2017/5/18
* desc : 文本+图片数量监听事件接口
* revise:
* </pre>
*/
public interface OnHyperChangeListener {
/**
* 文本+图片数量监听
* @param contentLength 文字长度
* @param imageLength 图片数量
*/
void onImageClick(int contentLength, int imageLength);
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
YCCustomTextLib/src/main/java/com/ns/yc/yccustomtextlib/edit/inter/OnHyperEditListener.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
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.
*/
package com.ns.yc.yccustomtextlib.edit.inter;
import android.view.View;
/**
* <pre>
* @author yangchong
* blog : https://github.com/yangchong211/YCStatusBar
* time : 2017/5/18
* desc : 自定义点击和删除事件接口
* revise:
* </pre>
*/
public interface OnHyperEditListener {
/**
* 图片点击事件
* @param view view
* @param imagePath 图片地址
*/
void onImageClick(View view, String imagePath);
/**
* 图片删除成功回调事件
* @param imagePath 图片地址
*/
void onRtImageDelete(String imagePath);
/**
* 图片删除图片点击事件
* @param view view
*/
void onImageCloseClick(View view);
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
YCCustomTextLib/src/main/java/com/ns/yc/yccustomtextlib/edit/inter/OnHyperTextListener.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
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.
*/
package com.ns.yc.yccustomtextlib.edit.inter;
import android.view.View;
/**
* <pre>
* @author yangchong
* blog : https://github.com/yangchong211/YCStatusBar
* time : 2017/5/18
* desc : 自定义点击和删除事件接口
* revise:
* </pre>
*/
public interface OnHyperTextListener {
/**
* 图片点击事件
* @param view view
* @param imagePath 图片地址
*/
void onImageClick(View view, String imagePath);
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
YCCustomTextLib/src/main/java/com/ns/yc/yccustomtextlib/edit/manager/HyperManager.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
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.
*/
package com.ns.yc.yccustomtextlib.edit.manager;
import android.widget.ImageView;
import com.ns.yc.yccustomtextlib.edit.inter.ImageLoader;
import com.ns.yc.yccustomtextlib.edit.view.HyperImageView;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2016/3/31
* desc : 图片loader管理者,使用单利
* revise: 暴露给开发者调用,将请求图片的过程暴露给开发者,便于维护
* </pre>
*/
public final class HyperManager {
private static volatile HyperManager instance;
private ImageLoader imageLoader;
/**
* 使用dcl双重校验方式获取单利对象
* 优点:在并发量不多,安全性不高的情况下或许能很完美运行单例模式
* 缺点:不同平台编译过程中可能会存在严重安全隐患。
* 在JDK1.5之后,官方给出了volatile关键字可以解决,多线程下执行顺序
* @return 返回对象
*/
public static HyperManager getInstance(){
//第一层判断是为了避免不必要的同步
if (instance == null){
synchronized (HyperManager.class){
//第二层的判断是为了在null的情况下才创建实例
if (instance == null){
instance = new HyperManager();
}
}
}
return instance;
}
/*
* 利用面向对象思想,将图片的设置和加载都使用manager完成,让代码逻辑和业务逻辑分离
*/
/**
* 设置加载loader
* @param imageLoader loader
*/
public void setImageLoader(ImageLoader imageLoader){
this.imageLoader = imageLoader;
}
/**
* 设置图片
* @param imagePath 地址
* @param imageView 图片view
* @param imageHeight 图片高度
*/
public void loadImage(String imagePath, HyperImageView imageView, int imageHeight){
if (imageLoader != null){
imageLoader.loadImage(imagePath, imageView, imageHeight);
}
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
YCCustomTextLib/src/main/java/com/ns/yc/yccustomtextlib/edit/model/HyperEditData.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
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.
*/
package com.ns.yc.yccustomtextlib.edit.model;
import java.io.Serializable;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2016/3/31
* desc : 富文本实体类
* revise: 目前就支持简单的富文本,文字+图片
* </pre>
*/
public class HyperEditData implements Serializable {
/**
* 富文本输入文字内容
*/
private String inputStr;
/**
* 富文本输入图片地址
*/
private String imagePath;
/**
* 类型:1,代表文字;2,代表图片
*/
private int type;
public String getInputStr() {
return inputStr;
}
public void setInputStr(String inputStr) {
this.inputStr = inputStr;
}
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
YCCustomTextLib/src/main/java/com/ns/yc/yccustomtextlib/edit/span/BoldItalicSpan.java | Java | package com.ns.yc.yccustomtextlib.edit.span;
import android.graphics.Typeface;
import android.text.style.StyleSpan;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2019/07/18
* desc : 加粗斜体
* revise:
* </pre>
*/
public class BoldItalicSpan extends StyleSpan implements InterInlineSpan {
private String type;
public BoldItalicSpan() {
super(Typeface.BOLD_ITALIC);
type = RichTypeEnum.BOLD_ITALIC;
}
@Override
public String getType() {
return type;
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
YCCustomTextLib/src/main/java/com/ns/yc/yccustomtextlib/edit/span/BoldStyleSpan.java | Java | package com.ns.yc.yccustomtextlib.edit.span;
import android.graphics.Typeface;
import android.text.style.StyleSpan;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2019/07/18
* desc : 加粗
* revise:
* </pre>
*/
public class BoldStyleSpan extends StyleSpan implements InterInlineSpan {
private String type;
public BoldStyleSpan() {
super(Typeface.BOLD);
type = RichTypeEnum.BOLD;
}
@Override
public String getType() {
return type;
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
YCCustomTextLib/src/main/java/com/ns/yc/yccustomtextlib/edit/span/InterInlineSpan.java | Java | package com.ns.yc.yccustomtextlib.edit.span;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2019/07/18
* desc : 接口
* revise:
* </pre>
*/
public interface InterInlineSpan {
@RichTypeEnum
String getType();
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
YCCustomTextLib/src/main/java/com/ns/yc/yccustomtextlib/edit/span/ItalicStyleSpan.java | Java | package com.ns.yc.yccustomtextlib.edit.span;
import android.graphics.Typeface;
import android.text.style.StyleSpan;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2019/07/18
* desc : 斜体
* revise:
* </pre>
*/
public class ItalicStyleSpan extends StyleSpan implements InterInlineSpan {
private String type;
public ItalicStyleSpan() {
super(Typeface.ITALIC);
type = RichTypeEnum.ITALIC;
}
@Override
public String getType() {
return type;
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
YCCustomTextLib/src/main/java/com/ns/yc/yccustomtextlib/edit/span/RichTypeEnum.java | Java | package com.ns.yc.yccustomtextlib.edit.span;
import android.support.annotation.StringDef;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2019/07/18
* desc : span枚举
* revise: 后期逐步把功能完善
* </pre>
*/
@Retention(RetentionPolicy.SOURCE)
@StringDef({RichTypeEnum.BOLD, RichTypeEnum.ITALIC, RichTypeEnum.STRIKE_THROUGH,
RichTypeEnum.UNDERLINE, RichTypeEnum.INLINE_IMAGE_SPAN, RichTypeEnum.BLOCK_HEADLINE,
RichTypeEnum.BLOCK_QUOTE, RichTypeEnum.BLOCK_NORMAL_TEXT,RichTypeEnum.BOLD_ITALIC})
public @interface RichTypeEnum {
/**
* 加粗
*/
String BOLD = "bold";
/**
* 斜体
*/
String ITALIC = "italic";
/**
* 粗斜体
*/
String BOLD_ITALIC = "bold_italic";
/**
* 删除线
*/
String STRIKE_THROUGH = "strike_through";
/**
* 下划线
*/
String UNDERLINE = "underline";
/**
* 行内ImageSpan
*/
String INLINE_IMAGE_SPAN = "inline_image_span";
/**
* 段落标题
*/
String BLOCK_HEADLINE = "block_headline";
/**
* 段落引用
*/
String BLOCK_QUOTE = "block_quote";
/**
* 段落普通文本(但是可能包含行内样式)
*/
String BLOCK_NORMAL_TEXT = "block_normal_text";
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
YCCustomTextLib/src/main/java/com/ns/yc/yccustomtextlib/edit/span/SpanTextHelper.java | Java | package com.ns.yc.yccustomtextlib.edit.span;
import android.text.Editable;
import android.widget.EditText;
import com.ns.yc.yccustomtextlib.edit.style.BoldItalicStyle;
import com.ns.yc.yccustomtextlib.edit.style.BoldStyle;
import com.ns.yc.yccustomtextlib.edit.style.ItalicStyle;
import com.ns.yc.yccustomtextlib.edit.style.StrikeThroughStyle;
import com.ns.yc.yccustomtextlib.edit.style.UnderlineStyle;
import com.ns.yc.yccustomtextlib.utils.HyperLogUtils;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2019/12/24
* desc : span帮助工具类
* revise:
* </pre>
*/
public class SpanTextHelper {
private static volatile SpanTextHelper helper;
public static SpanTextHelper getInstance(){
if (helper == null){
synchronized (SpanTextHelper.class){
if (helper == null){
helper = new SpanTextHelper();
}
}
}
return helper;
}
/**
* 修改加粗样式
*/
public void bold(EditText lastFocusEdit) {
//获取editable对象
Editable editable = lastFocusEdit.getEditableText();
//获取当前选中的起始位置
int start = lastFocusEdit.getSelectionStart();
//获取当前选中的末尾位置
int end = lastFocusEdit.getSelectionEnd();
HyperLogUtils.i("bold select Start:" + start + " end: " + end);
if (checkNormalStyle(start, end)) {
return;
}
new BoldStyle().applyStyle(editable, start, end);
}
/**
* 修改斜体样式
*/
public void italic(EditText lastFocusEdit) {
Editable editable = lastFocusEdit.getEditableText();
int start = lastFocusEdit.getSelectionStart();
int end = lastFocusEdit.getSelectionEnd();
HyperLogUtils.i("italic select Start:" + start + " end: " + end);
if (checkNormalStyle(start, end)) {
return;
}
new ItalicStyle().applyStyle(editable, start, end);
}
/**
* 修改加粗斜体样式
*/
public void boldItalic(EditText lastFocusEdit) {
Editable editable = lastFocusEdit.getEditableText();
int start = lastFocusEdit.getSelectionStart();
int end = lastFocusEdit.getSelectionEnd();
HyperLogUtils.i("boldItalic select Start:" + start + " end: " + end);
if (checkNormalStyle(start, end)) {
return;
}
new BoldItalicStyle().applyStyle(editable, start, end);
}
/**
* 修改删除线样式
*/
public void strikeThrough(EditText lastFocusEdit) {
Editable editable = lastFocusEdit.getEditableText();
int start = lastFocusEdit.getSelectionStart();
int end = lastFocusEdit.getSelectionEnd();
HyperLogUtils.i("strikeThrough select Start:" + start + " end: " + end);
if (checkNormalStyle(start, end)) {
return;
}
new StrikeThroughStyle().applyStyle(editable, start, end);
}
/**
* 修改下划线样式
*/
public void underline(EditText lastFocusEdit) {
Editable editable = lastFocusEdit.getEditableText();
int start = lastFocusEdit.getSelectionStart();
int end = lastFocusEdit.getSelectionEnd();
HyperLogUtils.i("underline select Start:" + start + " end: " + end);
if (checkNormalStyle(start, end)) {
return;
}
new UnderlineStyle().applyStyle(editable, start, end);
}
/**
* 判断是否是正常的样式
* @param start start
* @param end end
* @return
*/
private boolean checkNormalStyle(int start, int end) {
if (start > end) {
return true;
}
return false;
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
YCCustomTextLib/src/main/java/com/ns/yc/yccustomtextlib/edit/span/StrikeThroughSpan.java | Java | package com.ns.yc.yccustomtextlib.edit.span;
import android.text.style.StrikethroughSpan;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2019/07/18
* desc : 删除线
* revise:
* </pre>
*/
public class StrikeThroughSpan extends StrikethroughSpan implements InterInlineSpan {
private String type;
public StrikeThroughSpan() {
type = RichTypeEnum.STRIKE_THROUGH;
}
@Override
public String getType() {
return type;
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
YCCustomTextLib/src/main/java/com/ns/yc/yccustomtextlib/edit/span/UnderLineSpan.java | Java | package com.ns.yc.yccustomtextlib.edit.span;
import android.graphics.Typeface;
import android.text.style.UnderlineSpan;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2019/07/18
* desc : 下划线
* revise:
* </pre>
*/
public class UnderLineSpan extends UnderlineSpan implements InterInlineSpan {
private String type;
public UnderLineSpan() {
type = RichTypeEnum.UNDERLINE;
}
@Override
public String getType() {
return type;
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
YCCustomTextLib/src/main/java/com/ns/yc/yccustomtextlib/edit/state/TextEditorState.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
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.
*/
package com.ns.yc.yccustomtextlib.edit.state;
import android.os.Parcel;
import android.os.Parcelable;
import android.view.View;
import java.util.ArrayList;
/**
* <pre>
* @author yangchong
* blog : https://github.com/yangchong211/YCStatusBar
* time : 2017/5/18
* desc : 自定义BaseSavedState
* revise:
* </pre>
*/
public class TextEditorState extends View.BaseSavedState {
public int rtImageHeight;
public static final Creator<TextEditorState> CREATOR = new Creator<TextEditorState>() {
@Override
public TextEditorState createFromParcel(Parcel in) {
return new TextEditorState(in);
}
@Override
public TextEditorState[] newArray(int size) {
return new TextEditorState[size];
}
};
public TextEditorState(Parcelable superState) {
super(superState);
}
public TextEditorState(Parcel source) {
super(source);
rtImageHeight = source.readInt();
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeInt(rtImageHeight);
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
YCCustomTextLib/src/main/java/com/ns/yc/yccustomtextlib/edit/state/TextViewState.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
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.
*/
package com.ns.yc.yccustomtextlib.edit.state;
import android.os.Parcel;
import android.os.Parcelable;
import android.view.View;
/**
* <pre>
* @author yangchong
* blog : https://github.com/yangchong211
* time : 2017/5/18
* desc : 自定义BaseSavedState
* revise:
* </pre>
*/
public class TextViewState extends View.BaseSavedState {
int mLoadingTime;
int mLocation;
boolean isRunning;
public static final Creator<TextViewState> CREATOR = new Creator<TextViewState>() {
@Override
public TextViewState createFromParcel(Parcel in) {
return new TextViewState(in);
}
@Override
public TextViewState[] newArray(int size) {
return new TextViewState[size];
}
};
TextViewState(Parcelable superState) {
super(superState);
}
TextViewState(Parcel source) {
super(source);
mLoadingTime = source.readInt();
mLocation = source.readInt();
isRunning = source.readInt() == 1;
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeInt(mLoadingTime);
out.writeInt(mLocation);
out.writeInt(isRunning ? 1 : 0);
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
YCCustomTextLib/src/main/java/com/ns/yc/yccustomtextlib/edit/style/BoldItalicStyle.java | Java | package com.ns.yc.yccustomtextlib.edit.style;
import com.ns.yc.yccustomtextlib.edit.span.BoldItalicSpan;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2019/07/18
* desc : 加粗斜体
* revise:
* </pre>
*/
public class BoldItalicStyle extends NormalStyle<BoldItalicSpan> {
@Override
protected BoldItalicSpan newSpan() {
return new BoldItalicSpan();
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
YCCustomTextLib/src/main/java/com/ns/yc/yccustomtextlib/edit/style/BoldStyle.java | Java | package com.ns.yc.yccustomtextlib.edit.style;
import com.ns.yc.yccustomtextlib.edit.span.BoldStyleSpan;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2019/07/18
* desc : 加粗
* revise:
* </pre>
*/
public class BoldStyle extends NormalStyle<BoldStyleSpan> {
@Override
protected BoldStyleSpan newSpan() {
return new BoldStyleSpan();
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
YCCustomTextLib/src/main/java/com/ns/yc/yccustomtextlib/edit/style/ItalicStyle.java | Java | package com.ns.yc.yccustomtextlib.edit.style;
import com.ns.yc.yccustomtextlib.edit.span.ItalicStyleSpan;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2019/07/18
* desc : 斜体
* revise:
* </pre>
*/
public class ItalicStyle extends NormalStyle<ItalicStyleSpan> {
@Override
protected ItalicStyleSpan newSpan() {
return new ItalicStyleSpan();
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
YCCustomTextLib/src/main/java/com/ns/yc/yccustomtextlib/edit/style/NormalStyle.java | Java | package com.ns.yc.yccustomtextlib.edit.style;
import android.text.Editable;
import android.text.Spanned;
import android.util.Pair;
import java.lang.reflect.ParameterizedType;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2019/12/24
* desc : 样式抽象类
* revise:
* </pre>
*/
public abstract class NormalStyle<E> {
private Class<E> clazzE;
public NormalStyle() {
//利用反射
clazzE = (Class<E>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
/**
* 样式情况判断
* @param editable editable
* @param start start
* @param end end
*/
public void applyStyle(Editable editable, int start, int end) {
//获取 从 start 到 end 位置上所有的指定 class 类型的 Span数组
E[] spans = editable.getSpans(start, end, clazzE);
E existingSpan = null;
if (spans.length > 0) {
existingSpan = spans[0];
}
if (existingSpan == null) {
//当前选中内部无此样式,开始设置span样式
checkAndMergeSpan(editable, start, end, clazzE);
} else {
//获取 一个 span 的起始位置
int existingSpanStart = editable.getSpanStart(existingSpan);
//获取一个span 的结束位置
int existingSpanEnd = editable.getSpanEnd(existingSpan);
if (existingSpanStart <= start && existingSpanEnd >= end) {
//在一个 完整的 span 中
//当我们选中的区域在一段连续的 Bold 样式里面的时候,再次选择Bold将会取消样式
//删除 样式
removeStyle(editable, start, end, clazzE, true);
} else {
//当前选中区域存在了某某样式,需要合并样式
checkAndMergeSpan(editable, start, end, clazzE);
}
}
}
/**
* 移除样式
*
* setSpan(Object what, int start, int end, int flags); flag的四种类型
* Spanned.SPAN_EXCLUSIVE_EXCLUSIVE(前后都不包括);
* Spanned.SPAN_INCLUSIVE_EXCLUSIVE(前面包括,后面不包括);
* Spanned.SPAN_EXCLUSIVE_INCLUSIVE(前面不包括,后面包括);
* Spanned.SPAN_INCLUSIVE_INCLUSIVE(前后都包括)。
* @param editable editable
* @param start start
* @param end end
* @param clazzE clazz
* @param isSame 是否在 同一个 span 内部
*/
private void removeStyle(Editable editable, int start, int end, Class<E> clazzE, boolean isSame) {
E[] spans = editable.getSpans(start, end, clazzE);
if (spans.length > 0) {
if (isSame) {
//在 同一个 span 中
E span = spans[0];
if (null != span) {
// User stops the style, and wants to show
// un-UNDERLINE characters
int ess = editable.getSpanStart(span);
int ese = editable.getSpanEnd(span);
if (start >= ese) {
// User inputs to the end of the existing e span
// End existing e span
editable.removeSpan(span);
//设置 span 这里的 what 指的是 span 对象
//从 start 到 end 位置 设置 span 样式
//flags 为 Spanned中的变量
editable.setSpan(span, ess, start - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
} else if (start == ess && end == ese) {
// Case 1 desc:
// *BBBBBB*
// All selected, and un-showTodo e
editable.removeSpan(span);
} else if (start > ess && end < ese) {
// Case 2 desc:
// BB*BB*BB
// *BB* is selected, and un-showTodo e
editable.removeSpan(span);
E spanLeft = newSpan();
editable.setSpan(spanLeft, ess, start, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
E spanRight = newSpan();
editable.setSpan(spanRight, end, ese, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
} else if (start == ess && end < ese) {
// Case 3 desc:
// *BBBB*BB
// *BBBB* is selected, and un-showTodo e
editable.removeSpan(span);
E newSpan = newSpan();
editable.setSpan(newSpan, end, ese, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
} else if (start > ess && end == ese) {
// Case 4 desc:
// BB*BBBB*
// *BBBB* is selected, and un-showTodo e
editable.removeSpan(span);
E newSpan = newSpan();
editable.setSpan(newSpan, ess, start, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
} else {
Pair<E, E> firstAndLast = findFirstAndLast(editable, spans);
E firstSpan = firstAndLast.first;
E lastSpan = firstAndLast.second;
int leftStart = editable.getSpanStart(firstSpan);
int rightEnd = editable.getSpanEnd(lastSpan);
editable.removeSpan(firstSpan);
editable.setSpan(firstSpan, leftStart, start, Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
editable.removeSpan(lastSpan);
editable.setSpan(lastSpan,end,rightEnd,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
}
public Pair<E, E> findFirstAndLast(Editable editable, E[] targetSpans) {
if (targetSpans!=null && targetSpans.length > 0) {
E firstTargetSpan = targetSpans[0];
E lastTargetSpan = targetSpans[0];
int firstTargetSpanStart = editable.getSpanStart(firstTargetSpan);
int lastTargetSpanEnd = editable.getSpanEnd(firstTargetSpan);
for (E lns : targetSpans) {
int lnsStart = editable.getSpanStart(lns);
int lnsEnd = editable.getSpanEnd(lns);
if (lnsStart < firstTargetSpanStart) {
firstTargetSpan = lns;
firstTargetSpanStart = lnsStart;
}
if (lnsEnd > lastTargetSpanEnd) {
lastTargetSpan = lns;
lastTargetSpanEnd = lnsEnd;
}
}
return new Pair(firstTargetSpan, lastTargetSpan);
}
return null;
}
/**
* 边界判断与设置
* @param editable editable
* @param start start选择起始位置
* @param end end选择末尾位置
* @param clazzE clazz
*/
private void checkAndMergeSpan(Editable editable, int start, int end, Class<E> clazzE) {
E leftSpan = null;
E[] leftSpans = editable.getSpans(start, start, clazzE);
if (leftSpans.length > 0) {
leftSpan = leftSpans[0];
}
E rightSpan = null;
E[] rightSpans = editable.getSpans(end, end, clazzE);
if (rightSpans.length > 0) {
rightSpan = rightSpans[0];
}
//获取 两侧的 起始与 结束位置
int leftSpanStart = editable.getSpanStart(leftSpan);
int leftSpanEnd = editable.getSpanEnd(leftSpan);
int rightStart = editable.getSpanStart(rightSpan);
int rightSpanEnd = editable.getSpanEnd(rightSpan);
removeAllSpans(editable, start, end, clazzE);
if (leftSpan != null && rightSpan != null) {
if (leftSpanEnd == rightStart) {
//选中的两端是 连续的 样式
removeStyle(editable, start, end, clazzE, false);
} else {
E eSpan = newSpan();
editable.setSpan(eSpan, leftSpanStart, rightSpanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
} else if (leftSpan != null && rightSpan == null) {
E eSpan = newSpan();
editable.setSpan(eSpan, leftSpanStart, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
} else if (leftSpan == null && rightSpan != null) {
E eSpan = newSpan();
editable.setSpan(eSpan, start, rightSpanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
} else {
E eSpan = newSpan();
editable.setSpan(eSpan, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
protected abstract E newSpan();
private <E> void removeAllSpans(Editable editable, int start, int end, Class<E> clazzE) {
E[] allSpans = editable.getSpans(start, end, clazzE);
for (E span : allSpans) {
editable.removeSpan(span);
}
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
YCCustomTextLib/src/main/java/com/ns/yc/yccustomtextlib/edit/style/StrikeThroughStyle.java | Java | package com.ns.yc.yccustomtextlib.edit.style;
import com.ns.yc.yccustomtextlib.edit.span.StrikeThroughSpan;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2019/07/18
* desc : 删除线
* revise:
* </pre>
*/
public class StrikeThroughStyle extends NormalStyle<StrikeThroughSpan> {
@Override
protected StrikeThroughSpan newSpan() {
return new StrikeThroughSpan();
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
YCCustomTextLib/src/main/java/com/ns/yc/yccustomtextlib/edit/style/UnderlineStyle.java | Java | package com.ns.yc.yccustomtextlib.edit.style;
import com.ns.yc.yccustomtextlib.edit.span.UnderLineSpan;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2019/07/18
* desc : 下划线
* revise:
* </pre>
*/
public class UnderlineStyle extends NormalStyle<UnderLineSpan> {
@Override
protected UnderLineSpan newSpan() {
return new UnderLineSpan();
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
YCCustomTextLib/src/main/java/com/ns/yc/yccustomtextlib/edit/view/DeletableEditText.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
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.
*/
package com.ns.yc.yccustomtextlib.edit.view;
import android.content.Context;
import android.support.v7.widget.AppCompatEditText;
import android.util.AttributeSet;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import com.ns.yc.yccustomtextlib.edit.wrapper.DeleteInputConnection;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2016/3/31
* desc : 自定义EditText
* revise: 主要用途是处理软键盘回删按钮backSpace时回调OnKeyListener
* </pre>
*/
public class DeletableEditText extends AppCompatEditText {
private DeleteInputConnection inputConnection;
public DeletableEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public DeletableEditText(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public DeletableEditText(Context context) {
super(context);
init();
}
private void init(){
inputConnection = new DeleteInputConnection(null,true);
}
/**
* 当输入法和EditText建立连接的时候会通过这个方法返回一个InputConnection。
* 我们需要代理这个方法的父类方法生成的InputConnection并返回我们自己的代理类。
* @param outAttrs attrs
* @return
*/
@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
//inputConnection = new DeleteInputConnection(super.onCreateInputConnection(outAttrs), true);
inputConnection.setTarget(super.onCreateInputConnection(outAttrs));
return inputConnection;
}
/**
* 设置格键删除监听事件,主要是解决少部分手机,使用搜狗输入法无法响应当内容为空时的删除逻辑
* @param listener listener
*/
public void setBackSpaceListener(DeleteInputConnection.BackspaceListener listener){
inputConnection.setBackspaceListener(listener);
}
} | yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
YCCustomTextLib/src/main/java/com/ns/yc/yccustomtextlib/edit/view/HyperImageView.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
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.
*/
package com.ns.yc.yccustomtextlib.edit.view;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.v7.widget.AppCompatImageView;
import android.util.AttributeSet;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2016/3/31
* desc : 自定义ImageView
* revise: 可以存放Bitmap和Path等信息
* </pre>
*/
public class HyperImageView extends AppCompatImageView {
/**
* 是否显示边框
*/
private boolean showBorder = false;
/**
* 边框颜色
*/
private int borderColor = Color.GRAY;
/**
* 边框大小
*/
private int borderWidth = 5;
/**
* 文件绝对路径
*/
private String absolutePath;
/**
* bitmap图片
*/
private Bitmap bitmap;
/**
* 画笔
*/
private Paint paint;
public HyperImageView(Context context) {
this(context, null);
}
public HyperImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public HyperImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initData();
}
private void initData() {
//画笔
paint = new Paint();
//设置颜色
paint.setColor(borderColor);
//设置画笔的宽度
paint.setStrokeWidth(borderWidth);
//设置画笔的风格-不能设成填充FILL否则看不到图片
paint.setStyle(Paint.Style.STROKE);
}
public String getAbsolutePath() {
return absolutePath;
}
public void setAbsolutePath(String absolutePath) {
this.absolutePath = absolutePath;
}
public boolean isShowBorder() {
return showBorder;
}
public void setShowBorder(boolean showBorder) {
this.showBorder = showBorder;
}
public Bitmap getBitmap() {
return bitmap;
}
public void setBitmap(Bitmap bitmap) {
this.bitmap = bitmap;
}
public int getBorderColor() {
return borderColor;
}
public void setBorderColor(int borderColor) {
this.borderColor = borderColor;
}
public int getBorderWidth() {
return borderWidth;
}
public void setBorderWidth(int borderWidth) {
this.borderWidth = borderWidth;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (showBorder) {
//画边框
Rect rec = canvas.getClipBounds();
// 这两句可以使底部和右侧边框更大
//rec.bottom -= 2;
//rec.right -= 2;
canvas.drawRect(rec, paint);
}
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
YCCustomTextLib/src/main/java/com/ns/yc/yccustomtextlib/edit/view/HyperTextEditor.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
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.
*/
package com.ns.yc.yccustomtextlib.edit.view;
import android.animation.LayoutTransition;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.FrameLayout;
import android.widget.ScrollView;
import com.ns.yc.yccustomtextlib.edit.inter.OnHyperChangeListener;
import com.ns.yc.yccustomtextlib.edit.manager.HyperManager;
import com.ns.yc.yccustomtextlib.R;
import com.ns.yc.yccustomtextlib.edit.inter.OnHyperEditListener;
import com.ns.yc.yccustomtextlib.edit.model.HyperEditData;
import com.ns.yc.yccustomtextlib.edit.span.SpanTextHelper;
import com.ns.yc.yccustomtextlib.edit.state.TextEditorState;
import com.ns.yc.yccustomtextlib.utils.HyperLibUtils;
import com.ns.yc.yccustomtextlib.utils.HyperLogUtils;
import java.util.ArrayList;
import java.util.List;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2016/3/31
* desc : 编辑富文本
* revise:
* </pre>
*/
public class HyperTextEditor extends ScrollView {
/**
* editText常规padding是10dp
*/
private static final int EDIT_PADDING = 10;
/**
* 新生的view都会打一个tag,对每个view来说,这个tag是唯一的。
*/
private int viewTagIndex = 1;
/**
* 这个是所有子view的容器,scrollView内部的唯一一个ViewGroup
*/
private LinearLayout layout;
/**
* inflater对象
*/
private LayoutInflater inflater;
/**
* 所有EditText的软键盘监听器
*/
private OnKeyListener keyListener;
/**
* 图片右上角红叉按钮监听器
*/
private OnClickListener btnListener;
/**
* 所有EditText的焦点监听listener
*/
private OnFocusChangeListener focusListener;
/**
* 所有EditText的文本变化监听listener
*/
private TextWatcher textWatcher;
/**
* 最近被聚焦的EditText
*/
private EditText lastFocusEdit;
/**
* 只在图片View添加或remove时,触发transition动画
*/
private LayoutTransition mTransition;
private int editNormalPadding = 0;
/**
* 删除该图片,消失的图片控件索引
*/
private int disappearingImageIndex = 0;
/**
* 图片地址集合
*/
private ArrayList<String> imagePaths;
/**
* 关键词高亮
*/
private String keywords;
/**
* 插入的图片显示高度
*/
private int rtImageHeight;
/**
* 父控件的上和下padding
*/
private int topAndBottom;
/**
* 父控件的左和右padding
*/
private int leftAndRight;
/**
* 两张相邻图片间距
*/
private int rtImageBottom = 10;
/**
* 文字相关属性,初始提示信息,文字大小和颜色
*/
private String rtTextInitHint = "请输入内容";
/**
* 文字大小
*/
private int rtTextSize = 16;
/**
* 文字颜色
*/
private int rtTextColor = Color.parseColor("#757575");
private int rtHintTextColor = Color.parseColor("#B0B1B8");
/**
* 文字行间距
*/
private int rtTextLineSpace = 8;
/**
* 富文本的文字长度
*/
private int contentLength = 0;
/**
* 富文本的图片个数
*/
private int imageLength = 0;
/**
* 删除图片的位置
*/
private int delIconLocation = 0;
/**
* 自定义输入文本的光标颜色
*/
private int cursorColor;
private OnHyperEditListener onHyperListener;
private OnHyperChangeListener onHyperChangeListener;
/**
* 保存重要信息
* @return
*/
@Nullable
@Override
protected Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
TextEditorState viewState = new TextEditorState(superState);
viewState.rtImageHeight = rtImageHeight;
return viewState;
}
/**
* 复现
* @param state state
*/
@Override
protected void onRestoreInstanceState(Parcelable state) {
TextEditorState viewState = (TextEditorState) state;
rtImageHeight = viewState.rtImageHeight;
super.onRestoreInstanceState(viewState.getSuperState());
requestLayout();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (mTransition!=null){
//移除Layout变化监听
mTransition.removeTransitionListener(transitionListener);
HyperLogUtils.d("HyperTextEditor----onDetachedFromWindow------移除Layout变化监听");
}
}
public HyperTextEditor(Context context) {
this(context, null);
}
public HyperTextEditor(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public HyperTextEditor(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
imagePaths = new ArrayList<>();
inflater = LayoutInflater.from(context);
initAttrs(context,attrs);
initLayoutView(context);
initListener();
initFirstEditText(context);
}
private void initLayoutView(Context context) {
//初始化layout
layout = new LinearLayout(context);
layout.setOrientation(LinearLayout.VERTICAL);
//禁止载入动画
setUpLayoutTransitions();
LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
//设置间距,防止生成图片时文字太靠边,不能用margin,否则有黑边
layout.setPadding(leftAndRight,topAndBottom,leftAndRight,topAndBottom);
addView(layout, layoutParams);
}
/**
* 初始化自定义属性
* @param context context上下文
* @param attrs attrs属性
*/
private void initAttrs(Context context, AttributeSet attrs) {
//获取自定义属性
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.HyperTextEditor);
topAndBottom = ta.getDimensionPixelSize(R.styleable.HyperTextEditor_editor_layout_top_bottom, 15);
leftAndRight = ta.getDimensionPixelSize(R.styleable.HyperTextEditor_editor_layout_right_left, 40);
rtImageHeight = ta.getDimensionPixelSize(R.styleable.HyperTextEditor_editor_image_height, 250);
rtImageBottom = ta.getDimensionPixelSize(R.styleable.HyperTextEditor_editor_image_bottom, 10);
rtTextSize = ta.getDimensionPixelSize(R.styleable.HyperTextEditor_editor_text_size, 16);
rtTextLineSpace = ta.getDimensionPixelSize(R.styleable.HyperTextEditor_editor_text_line_space, 8);
rtTextColor = ta.getColor(R.styleable.HyperTextEditor_editor_text_color, Color.parseColor("#757575"));
rtHintTextColor = ta.getColor(R.styleable.HyperTextEditor_editor_hint_text_color,Color.parseColor("#B0B1B8"));
rtTextInitHint = ta.getString(R.styleable.HyperTextEditor_editor_text_init_hint);
delIconLocation = ta.getInt(R.styleable.HyperTextEditor_editor_del_icon_location,0);
cursorColor = ta.getColor(R.styleable.HyperTextEditor_editor_text_cursor_color,Color.parseColor("#FF434F"));
ta.recycle();
}
private void initListener() {
// 初始化键盘退格监听,主要用来处理点击回删按钮时,view的一些列合并操作
keyListener = new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
//KeyEvent.KEYCODE_DEL 删除插入点之前的字符
if (event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_DEL) {
EditText edit = (EditText) v;
//处于退格删除的逻辑
onBackspacePress(edit);
}
return false;
}
};
// 图片删除图标叉掉处理
btnListener = new OnClickListener() {
@Override
public void onClick(View v) {
if (v instanceof HyperImageView){
HyperImageView imageView = (HyperImageView)v;
// 开放图片点击接口
if (onHyperListener != null){
onHyperListener.onImageClick(imageView, imageView.getAbsolutePath());
}
} else if (v instanceof ImageView){
FrameLayout parentView = (FrameLayout) v.getParent();
// 图片删除图片点击事件
if (onHyperListener != null){
onHyperListener.onImageCloseClick(parentView);
}
//onImageCloseClick(parentView);
}
}
};
focusListener = new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
lastFocusEdit = (EditText) v;
HyperLogUtils.d("HyperTextEditor---onFocusChange--"+lastFocusEdit);
}
}
};
textWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
addHyperEditorChangeListener();
HyperLogUtils.d("HyperTextEditor---onTextChanged--文字--"+contentLength+"--图片-"+imageLength);
}
@Override
public void afterTextChanged(Editable s) {
}
};
}
private void initFirstEditText(Context context) {
LinearLayout.LayoutParams firstEditParam = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
int padding = HyperLibUtils.dip2px(context, EDIT_PADDING);
EditText firstEdit = createEditText(rtTextInitHint, padding);
layout.addView(firstEdit, firstEditParam);
lastFocusEdit = firstEdit;
}
/**
* 处理软键盘backSpace回退事件
* @param editText 光标所在的文本输入框
*/
@SuppressLint("SetTextI18n")
private void onBackspacePress(EditText editText) {
if (editText==null){
return;
}
try {
int startSelection = editText.getSelectionStart();
// 只有在光标已经顶到文本输入框的最前方,在判定是否删除之前的图片,或两个View合并
if (startSelection == 0) {
//获取当前控件在layout父容器中的索引
int editIndex = layout.indexOfChild(editText);
// 如果editIndex-1<0,
View preView = layout.getChildAt(editIndex - 1);
if (null != preView) {
if (preView instanceof FrameLayout) {
// 光标EditText的上一个view对应的是图片,删除图片操作
onImageCloseClick(preView);
} else if (preView instanceof EditText) {
// 光标EditText的上一个view对应的还是文本框EditText,删除文字操作
String str1 = editText.getText().toString();
EditText preEdit = (EditText) preView;
String str2 = preEdit.getText().toString();
// 合并文本view时,不需要transition动画
layout.setLayoutTransition(null);
//移除editText文本控件
layout.removeView(editText);
// 恢复transition动画
layout.setLayoutTransition(mTransition);
// 文本合并操作
preEdit.setText(str2 + str1);
preEdit.requestFocus();
preEdit.setSelection(str2.length(), str2.length());
lastFocusEdit = preEdit;
}
} else {
HyperLogUtils.d("HyperTextEditor----onBackspacePress------没有上一个view");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 处理图片上删除的点击事件
* 删除类型 0代表backspace删除 1代表按红叉按钮删除
* @param view 整个image对应的relativeLayout view
*/
public void onImageCloseClick(View view) {
try {
//判断过渡动画是否结束,只能等到结束才可以操作
if (!mTransition.isRunning()) {
//获取当前要删除图片控件的索引值
disappearingImageIndex = layout.indexOfChild(view);
//删除文件夹里的图片
List<HyperEditData> dataList = buildEditData();
//获取要删除图片控件的数据
HyperEditData editData = dataList.get(disappearingImageIndex);
if (editData.getImagePath() != null){
if (onHyperListener != null){
onHyperListener.onRtImageDelete(editData.getImagePath());
}
//SDCardUtil.deleteFile(editData.imagePath);
//从图片集合中移除图片链接
imagePaths.remove(editData.getImagePath());
addHyperEditorChangeListener();
}
//然后移除当前view
layout.removeView(view);
//合并上下EditText内容
mergeEditText();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 监听富文本:文字+图片数量变化
* 分别在图片插入,图片删除,以及文本变化时添加监听事件
*/
private void addHyperEditorChangeListener() {
getContentAndImageCount();
int contentLength = getContentLength();
int imageLength = getImageLength();
if (onHyperChangeListener!=null){
onHyperChangeListener.onImageClick(contentLength,imageLength);
}
}
/**
* 清空所有布局
*/
public void clearAllLayout(){
if (layout!=null){
layout.removeAllViews();
}
}
/**
* 获取索引位置
*/
public int getLastIndex(){
if (layout!=null){
int childCount = layout.getChildCount();
return childCount;
}
return -1;
}
/**
* 添加生成文本输入框
* @param hint 内容
* @param paddingTop 到顶部高度
* @return
*/
private EditText createEditText(String hint, int paddingTop) {
EditText editText = new DeletableEditText(getContext());
LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
editText.setLayoutParams(layoutParams);
editText.setTextSize(16);
editText.setTextColor(Color.parseColor("#616161"));
editText.setCursorVisible(true);
editText.setBackground(null);
editText.setOnKeyListener(keyListener);
editText.setOnFocusChangeListener(focusListener);
editText.addTextChangedListener(textWatcher);
editText.setTag(viewTagIndex++);
editText.setPadding(editNormalPadding, paddingTop, editNormalPadding, paddingTop);
editText.setHint(hint);
editText.setTextSize(TypedValue.COMPLEX_UNIT_PX, rtTextSize);
editText.setTextColor(rtTextColor);
editText.setHintTextColor(rtHintTextColor);
editText.setLineSpacing(rtTextLineSpace, 1.0f);
HyperLibUtils.setCursorDrawableColor(editText, cursorColor);
return editText;
}
/**
* 生成图片View
*/
private FrameLayout createImageLayout() {
FrameLayout layout = (FrameLayout) inflater.inflate(R.layout.hte_edit_imageview, null);
layout.setTag(viewTagIndex++);
ImageView closeView = layout.findViewById(R.id.image_close);
FrameLayout.LayoutParams layoutParams = (LayoutParams) closeView.getLayoutParams();
layoutParams.bottomMargin = HyperLibUtils.dip2px(layout.getContext(),10.0f);
switch (delIconLocation){
//左上角
case 1:
layoutParams.gravity = Gravity.TOP | Gravity.START;
closeView.setLayoutParams(layoutParams);
break;
//右上角
case 2:
layoutParams.gravity = Gravity.TOP | Gravity.END;
closeView.setLayoutParams(layoutParams);
break;
//左下角
case 3:
layoutParams.gravity = Gravity.BOTTOM | Gravity.START;
closeView.setLayoutParams(layoutParams);
break;
//右下角
case 4:
layoutParams.gravity = Gravity.BOTTOM | Gravity.END;
closeView.setLayoutParams(layoutParams);
break;
//其他右下角
default:
layoutParams.gravity = Gravity.BOTTOM | Gravity.END;
closeView.setLayoutParams(layoutParams);
break;
}
closeView.setTag(layout.getTag());
closeView.setOnClickListener(btnListener);
HyperImageView imageView = layout.findViewById(R.id.edit_imageView);
imageView.setOnClickListener(btnListener);
return layout;
}
/**
* 插入一张图片
* @param imagePath 图片路径地址
*/
public synchronized void insertImage(String imagePath) {
//bitmap == null时,可能是网络图片,不能做限制
if (TextUtils.isEmpty(imagePath)){
return;
}
try {
//lastFocusEdit获取焦点的EditText
String lastEditStr = lastFocusEdit.getText().toString();
//获取光标所在位置
int cursorIndex = lastFocusEdit.getSelectionStart();
//获取光标前面的字符串
String editStr1 = lastEditStr.substring(0, cursorIndex).trim();
//获取光标后的字符串
String editStr2 = lastEditStr.substring(cursorIndex).trim();
//获取焦点的EditText所在位置
int lastEditIndex = layout.indexOfChild(lastFocusEdit);
if (lastEditStr.length() == 0) {
//如果当前获取焦点的EditText为空,直接在EditText下方插入图片,并且插入空的EditText
addEditTextAtIndex(lastEditIndex + 1, "");
addImageViewAtIndex(lastEditIndex + 1, imagePath);
} else if (editStr1.length() == 0) {
//如果光标已经顶在了editText的最前面,则直接插入图片,并且EditText下移即可
addImageViewAtIndex(lastEditIndex, imagePath);
//同时插入一个空的EditText,防止插入多张图片无法写文字
addEditTextAtIndex(lastEditIndex + 1, "");
} else if (editStr2.length() == 0) {
// 如果光标已经顶在了editText的最末端,则需要添加新的imageView和EditText
addEditTextAtIndex(lastEditIndex + 1, "");
addImageViewAtIndex(lastEditIndex + 1, imagePath);
} else {
//如果光标已经顶在了editText的最中间,则需要分割字符串,分割成两个EditText,并在两个EditText中间插入图片
//把光标前面的字符串保留,设置给当前获得焦点的EditText(此为分割出来的第一个EditText)
lastFocusEdit.setText(editStr1);
//把光标后面的字符串放在新创建的EditText中(此为分割出来的第二个EditText)
addEditTextAtIndex(lastEditIndex + 1, editStr2);
//在第二个EditText的位置插入一个空的EditText,以便连续插入多张图片时,有空间写文字,第二个EditText下移
addEditTextAtIndex(lastEditIndex + 1, "");
//在空的EditText的位置插入图片布局,空的EditText下移
addImageViewAtIndex(lastEditIndex + 1, imagePath);
}
//隐藏小键盘
hideKeyBoard();
//监听富文本:文字+图片数量变化
addHyperEditorChangeListener();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 隐藏小键盘
*/
private void hideKeyBoard() {
InputMethodManager imm = (InputMethodManager)
getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null && lastFocusEdit != null) {
imm.hideSoftInputFromWindow(lastFocusEdit.getWindowToken(), 0);
}
}
public void setKeywords(String keywords) {
this.keywords = keywords;
}
/**
* 在特定位置插入EditText
* @param index 位置
* @param editStr EditText显示的文字
*/
public synchronized void addEditTextAtIndex(final int index, CharSequence editStr) {
try {
EditText editText = createEditText("插入文字", EDIT_PADDING);
if (!TextUtils.isEmpty(keywords)) {
//搜索关键词高亮
SpannableStringBuilder textStr = HyperLibUtils.highlight(
editStr.toString(), keywords , Color.parseColor("#EE5C42"));
editText.setText(textStr);
} else if (!TextUtils.isEmpty(editStr)) {
//判断插入的字符串是否为空,如果没有内容则显示hint提示信息
editText.setText(editStr);
}
// 请注意此处,EditText添加、或删除不触动Transition动画
layout.setLayoutTransition(null);
layout.addView(editText, index);
// remove之后恢复transition动画
layout.setLayoutTransition(mTransition);
//插入新的EditText之后,修改lastFocusEdit的指向
lastFocusEdit = editText;
//获取焦点
lastFocusEdit.requestFocus();
//将光标移至文字指定索引处
lastFocusEdit.setSelection(editStr.length(), editStr.length());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 在特定位置添加ImageView
*/
public synchronized void addImageViewAtIndex(final int index, final String imagePath) {
if (TextUtils.isEmpty(imagePath)){
return;
}
try {
imagePaths.add(imagePath);
final FrameLayout imageLayout = createImageLayout();
HyperImageView imageView = imageLayout.findViewById(R.id.edit_imageView);
imageView.setAbsolutePath(imagePath);
HyperManager.getInstance().loadImage(imagePath, imageView, rtImageHeight);
layout.addView(imageLayout, index);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 初始化transition动画
*/
private void setUpLayoutTransitions() {
mTransition = new LayoutTransition();
//添加Layout变化监听
mTransition.addTransitionListener(transitionListener);
//若向ViewGroup中添加一个ImageView,ImageView对象可以设置动画(即APPEARING 动画形式),
//ViewGroup中的其它ImageView对象此时移动到新的位置的过程中也可以设置相关的动画(即CHANGE_APPEARING 动画形式)。
mTransition.enableTransitionType(LayoutTransition.APPEARING);
//设置整个Layout变换动画时间
mTransition.setDuration(300);
layout.setLayoutTransition(mTransition);
}
private LayoutTransition.TransitionListener transitionListener =
new LayoutTransition.TransitionListener() {
/**
* LayoutTransition某一类型动画开始
* @param transition transition
* @param container container容器
* @param view view控件
* @param transitionType 类型
*/
@Override
public void startTransition(LayoutTransition transition, ViewGroup container,
View view, int transitionType) {
}
/**
* LayoutTransition某一类型动画结束
* @param transition transition
* @param container container容器
* @param view view控件
* @param transitionType 类型
*/
@Override
public void endTransition(LayoutTransition transition,
ViewGroup container, View view, int transitionType) {
if (!transition.isRunning() && transitionType == LayoutTransition.CHANGE_DISAPPEARING) {
// transition动画结束,合并EditText
mergeEditText();
}
}
};
/**
* 图片删除的时候,如果上下方都是EditText,则合并处理
*/
private void mergeEditText() {
try {
View preView = layout.getChildAt(disappearingImageIndex - 1);
View nextView = layout.getChildAt(disappearingImageIndex);
if (preView instanceof EditText && nextView instanceof EditText) {
EditText preEdit = (EditText) preView;
EditText nextEdit = (EditText) nextView;
String str1 = preEdit.getText().toString();
String str2 = nextEdit.getText().toString();
String mergeText = "";
if (str2.length() > 0) {
mergeText = str1 + "\n" + str2;
} else {
mergeText = str1;
}
layout.setLayoutTransition(null);
layout.removeView(nextEdit);
preEdit.setText(mergeText);
//设置光标的定位
preEdit.requestFocus();
preEdit.setSelection(str1.length(), str1.length());
//设置动画
layout.setLayoutTransition(mTransition);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 对外提供的接口, 生成编辑数据上传
*/
public List<HyperEditData> buildEditData() {
List<HyperEditData> dataList = new ArrayList<>();
try {
int num = layout.getChildCount();
for (int index = 0; index < num; index++) {
View itemView = layout.getChildAt(index);
HyperEditData hyperEditData = new HyperEditData();
if (itemView instanceof EditText) {
//文本
EditText item = (EditText) itemView;
hyperEditData.setInputStr(item.getText().toString());
hyperEditData.setType(1);
} else if (itemView instanceof FrameLayout) {
//图片
HyperImageView item = itemView.findViewById(R.id.edit_imageView);
hyperEditData.setImagePath(item.getAbsolutePath());
hyperEditData.setType(2);
}
dataList.add(hyperEditData);
}
} catch (Exception e) {
e.printStackTrace();
}
HyperLogUtils.d("HyperTextEditor----buildEditData------dataList---"+dataList.size());
return dataList;
}
/**
* 用于统计文本文字的数量和图片的数量
*/
public void getContentAndImageCount() {
contentLength = 0;
imageLength = 0;
if (layout==null){
return;
}
try {
int num = layout.getChildCount();
for (int index = 0; index < num; index++) {
View itemView = layout.getChildAt(index);
if (itemView instanceof EditText) {
//文本
EditText item = (EditText) itemView;
if (item.getText()!=null){
String string = item.getText().toString().trim();
int length = string.length();
contentLength = contentLength + length;
}
} else if (itemView instanceof FrameLayout) {
//图片
imageLength++;
}
}
} catch (Exception e) {
e.printStackTrace();
}
HyperLogUtils.d("HyperTextEditor----buildEditData------dataList---");
}
/**
* 上传图片成功之后,替换本地图片路径
* @param url 网络图片
* @param localPath 本地图片
*/
public void setImageUrl(String url,String localPath) {
HyperLogUtils.d("HyperTextEditor----setImageUrl1------"+url+"----"+localPath);
if (layout==null){
return;
}
try {
int num = layout.getChildCount();
for (int index = 0; index < num; index++) {
View itemView = layout.getChildAt(index);
if (itemView instanceof FrameLayout) {
//图片控件,需要替换图片url
HyperImageView item = itemView.findViewById(R.id.edit_imageView);
if (item.getAbsolutePath().equals(localPath)){
item.setAbsolutePath(url);
HyperLogUtils.d("HyperTextEditor----setImageUrl2------"+url+"----"+localPath);
return;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void setOnHyperListener(OnHyperEditListener listener){
this.onHyperListener = listener;
}
public void setOnHyperChangeListener(OnHyperChangeListener onHyperChangeListener) {
this.onHyperChangeListener = onHyperChangeListener;
}
public EditText getLastFocusEdit() {
return lastFocusEdit;
}
public int getContentLength() {
return contentLength;
}
public int getImageLength() {
return imageLength;
}
/**
* 修改加粗样式
*/
public void bold() {
SpanTextHelper.getInstance().bold(lastFocusEdit);
}
/**
* 修改斜体样式
*/
public void italic() {
SpanTextHelper.getInstance().italic(lastFocusEdit);
}
/**
* 修改加粗斜体样式
*/
public void boldItalic() {
SpanTextHelper.getInstance().boldItalic(lastFocusEdit);
}
/**
* 修改删除线样式
*/
public void strikeThrough() {
SpanTextHelper.getInstance().strikeThrough(lastFocusEdit);
}
/**
* 修改下划线样式
*/
public void underline() {
SpanTextHelper.getInstance().underline(lastFocusEdit);
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
YCCustomTextLib/src/main/java/com/ns/yc/yccustomtextlib/edit/view/HyperTextView.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
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.
*/
package com.ns.yc.yccustomtextlib.edit.view;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import com.ns.yc.yccustomtextlib.R;
import com.ns.yc.yccustomtextlib.edit.inter.OnHyperTextListener;
import com.ns.yc.yccustomtextlib.edit.manager.HyperManager;
import com.ns.yc.yccustomtextlib.edit.model.HyperEditData;
import com.ns.yc.yccustomtextlib.utils.HyperLibUtils;
import com.ns.yc.yccustomtextlib.utils.HyperLogUtils;
import java.util.ArrayList;
import java.util.List;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2016/3/31
* desc : 显示富文本
* revise:
* </pre>
*/
public class HyperTextView extends ScrollView {
/**
* 常规padding是10dp
*/
private static final int EDIT_PADDING = 10;
/**
* 新生的view都会打一个tag,对每个view来说,这个tag是唯一的
*/
private int viewTagIndex = 1;
/**
* 这个是所有子view的容器,scrollView内部的唯一一个ViewGroup
*/
private LinearLayout allLayout;
private LayoutInflater inflater;
private int editNormalPadding = 0;
/**
* 图片点击事件
*/
private OnClickListener btnListener;
/**
* 图片地址集合
*/
private ArrayList<String> imagePaths;
/**
* 关键词高亮
*/
private String keywords;
private OnHyperTextListener onHyperTextListener;
/**
* 插入的图片显示高度,为0显示原始高度
*/
private int rtImageHeight = 0;
/**
* 两张相邻图片间距
*/
private int rtImageBottom = 10;
/**
* 父控件的上和下padding
*/
private int topAndBottom;
/**
* 父控件的左和右padding
*/
private int leftAndRight;
/**
* 文字相关属性,初始提示信息,文字大小和颜色
*/
private String rtTextInitHint = "没有内容";
/**
* 相当于16sp
*/
private int rtTextSize = 16;
private int rtTextColor = Color.parseColor("#757575");
/**
* 相当于8dp
*/
private int rtTextLineSpace = 8;
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
HyperLogUtils.d("HyperTextView----onDetachedFromWindow------");
}
public HyperTextView(Context context) {
this(context, null);
}
public HyperTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public HyperTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
imagePaths = new ArrayList<>();
inflater = LayoutInflater.from(context);
//获取自定义属性
initAttrs(context,attrs);
initLayoutView(context);
initListener();
initFirstTextView(context);
}
/**
* 初始化自定义属性
* @param context context上下文
* @param attrs attrs属性
*/
private void initAttrs(Context context, AttributeSet attrs) {
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.HyperTextView);
rtImageHeight = ta.getInteger(R.styleable.HyperTextView_ht_view_image_height, 0);
topAndBottom = ta.getDimensionPixelSize(R.styleable.HyperTextView_ht_view_top_bottom, 15);
leftAndRight = ta.getDimensionPixelSize(R.styleable.HyperTextView_ht_view_right_left, 40);
rtImageBottom = ta.getInteger(R.styleable.HyperTextView_ht_view_image_bottom, 10);
rtTextSize = ta.getDimensionPixelSize(R.styleable.HyperTextView_ht_view_text_size, 16);
rtTextLineSpace = ta.getDimensionPixelSize(R.styleable.HyperTextView_ht_view_text_line_space, 8);
rtTextColor = ta.getColor(R.styleable.HyperTextView_ht_view_text_color, Color.parseColor("#757575"));
rtTextInitHint = ta.getString(R.styleable.HyperTextView_ht_view_text_init_hint);
ta.recycle();
}
private void initLayoutView(Context context) {
//初始化allLayout
allLayout = new LinearLayout(context);
allLayout.setOrientation(LinearLayout.VERTICAL);
//allLayout.setBackgroundColor(Color.WHITE);//去掉背景
LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
//设置间距,防止生成图片时文字太靠边,不能用margin,否则有黑边
allLayout.setPadding(leftAndRight,topAndBottom,leftAndRight,topAndBottom);
addView(allLayout, layoutParams);
}
private void initListener() {
btnListener = new OnClickListener() {
@Override
public void onClick(View v) {
if (v instanceof HyperImageView){
HyperImageView imageView = (HyperImageView) v;
//int currentItem = imagePaths.indexOf(imageView.getAbsolutePath());
// 开放图片点击接口
if (onHyperTextListener != null){
onHyperTextListener.onImageClick(imageView, imageView.getAbsolutePath());
}
}
}
};
}
private void initFirstTextView(Context context) {
LinearLayout.LayoutParams firstEditParam = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
int padding = HyperLibUtils.dip2px(context, EDIT_PADDING);
TextView firstText = createTextView(rtTextInitHint,padding);
allLayout.addView(firstText, firstEditParam);
}
public void setOnHyperTextListener(OnHyperTextListener onRtImageClickListener) {
this.onHyperTextListener = onRtImageClickListener;
}
/**
* 清除所有的view
*/
public void clearAllLayout(){
if (allLayout!=null){
allLayout.removeAllViews();
}
}
/**
* 获得最后一个子view的位置
*/
public int getLastIndex(){
if (allLayout!=null){
int lastEditIndex = allLayout.getChildCount();
return lastEditIndex;
}
return -1;
}
/**
* 生成文本输入框
*/
private TextView createTextView(String hint, int paddingTop) {
TextView textView = new TextView(getContext());
LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
textView.setLayoutParams(layoutParams);
textView.setTextSize(16);
textView.setTextColor(Color.parseColor("#616161"));
textView.setTextIsSelectable(true);
textView.setBackground(null);
textView.setTag(viewTagIndex++);
textView.setPadding(editNormalPadding, paddingTop, editNormalPadding, paddingTop);
textView.setHint(hint);
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, rtTextSize);
textView.setLineSpacing(rtTextLineSpace, 1.0f);
textView.setTextColor(rtTextColor);
return textView;
}
/**
* 生成图片View
* @return view
*/
private RelativeLayout createImageLayout() {
RelativeLayout layout = (RelativeLayout) inflater.inflate(R.layout.edit_imageview, null);
layout.setTag(viewTagIndex++);
View closeView = layout.findViewById(R.id.image_close);
closeView.setVisibility(GONE);
HyperImageView imageView = layout.findViewById(R.id.edit_imageView);
imageView.setOnClickListener(btnListener);
return layout;
}
public void setKeywords(String keywords) {
this.keywords = keywords;
}
/**
* 在特定位置插入TextView
*
* @param index 位置
* @param editStr EditText显示的文字
*/
public synchronized void addTextViewAtIndex(final int index, CharSequence editStr) {
if (index==-1 && editStr == null || editStr.length()==0){
return;
}
try {
TextView textView = createTextView("", EDIT_PADDING);
if (!TextUtils.isEmpty(keywords)) {
//搜索关键词高亮
SpannableStringBuilder textStr = HyperLibUtils.highlight(
editStr.toString(), keywords,Color.parseColor("#EE5C42"));
textView.setText(textStr);
} else {
textView.setText(editStr);
}
allLayout.addView(textView, index);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 在特定位置添加ImageView
* @param index 索引值
* @param imagePath 图片地址
*/
public synchronized void addImageViewAtIndex(final int index, final String imagePath) {
if (index==-1){
return;
}
if (TextUtils.isEmpty(imagePath)){
return;
}
imagePaths.add(imagePath);
RelativeLayout imageLayout = createImageLayout();
if (imageLayout == null){
return;
}
final HyperImageView imageView = imageLayout.findViewById(R.id.edit_imageView);
imageView.setAbsolutePath(imagePath);
// 暴露给外部加载图片
HyperManager.getInstance().loadImage(imagePath, imageView, rtImageHeight);
// onActivityResult无法触发动画,此处post处理
allLayout.addView(imageLayout, index);
}
/**
* 在特定位置添加ImageView,折行
* @param index 索引值
* @param imagePath 图片地址
* @param isWordWrap 是否折行
*/
public synchronized void addImageViewAtIndex(final int index, String imagePath , boolean isWordWrap) {
if (index==-1){
return;
}
if(imagePath==null || imagePath.length()==0){
return;
}
Bitmap bmp = BitmapFactory.decodeFile(imagePath);
final RelativeLayout imageLayout = createImageLayout();
HyperImageView imageView = imageLayout.findViewById(R.id.edit_imageView);
//Picasso.with(getContext()).load(imagePath).centerCrop().into(imageView);
//Glide.with(getContext()).load(imagePath).crossFade().centerCrop().into(imageView);
//imageView.setImageBitmap(bmp); //
//imageView.setBitmap(bmp); //这句去掉,保留下面的图片地址即可,优化图片占用
imageView.setAbsolutePath(imagePath);
// 调整imageView的高度
int imageHeight = 500;
if (bmp != null) {
imageHeight = allLayout.getWidth() * bmp.getHeight() / bmp.getWidth();
// 使用之后,还是回收掉吧
bmp.recycle();
}
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, imageHeight);
lp.bottomMargin = 10;
imageView.setLayoutParams(lp);
allLayout.addView(imageLayout, index);
}
/**
* 对外提供的接口, 生成编辑数据上传
*/
public List<HyperEditData> buildEditData() {
List<HyperEditData> dataList = new ArrayList<>();
try {
int num = allLayout.getChildCount();
for (int index = 0; index < num; index++) {
View itemView = allLayout.getChildAt(index);
HyperEditData hyperEditData = new HyperEditData();
if (itemView instanceof TextView) {
//文本
TextView item = (TextView) itemView;
hyperEditData.setInputStr(item.getText().toString());
hyperEditData.setType(1);
} else if (itemView instanceof RelativeLayout) {
//图片
HyperImageView item = itemView.findViewById(R.id.edit_imageView);
hyperEditData.setImagePath(item.getAbsolutePath());
hyperEditData.setType(2);
}
dataList.add(hyperEditData);
}
} catch (Exception e) {
e.printStackTrace();
}
HyperLogUtils.d("HyperTextEditor----buildEditData------dataList---"+dataList.size());
return dataList;
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
YCCustomTextLib/src/main/java/com/ns/yc/yccustomtextlib/edit/wrapper/DeleteInputConnection.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
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.
*/
package com.ns.yc.yccustomtextlib.edit.wrapper;
import android.view.KeyEvent;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputConnectionWrapper;
import com.ns.yc.yccustomtextlib.utils.HyperLogUtils;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2019/07/18
* desc : 自定义InputConnectionWrapper
* revise:
* </pre>
*/
public class DeleteInputConnection extends InputConnectionWrapper {
private BackspaceListener mBackspaceListener;
public interface BackspaceListener {
/**
* @return true 代表消费了这个事件
* */
boolean onBackspace();
}
public void setBackspaceListener(BackspaceListener backspaceListener) {
this.mBackspaceListener = backspaceListener;
}
public DeleteInputConnection(InputConnection target, boolean mutable) {
super(target, mutable);
}
/**
* 提交文本
* 输入法输入了字符,包括表情,字母、文字、数字和符号等内容,会回调该方法
* @param text text
* @param newCursorPosition 新索引位置
* @return
*/
@Override
public boolean commitText(CharSequence text, int newCursorPosition) {
return super.commitText(text, newCursorPosition);
}
/**
* 按键事件
* 在commitText方法中,
* 如果执行父类的 commitText(即super.commitText(text, newCursorPosition))那么表示不拦截,
* 如果返回false则表示拦截
*
* 当有按键输入时,该方法会被回调。比如点击退格键时,搜狗输入法应该就是通过调用该方法,
* 发送keyEvent的,但谷歌输入法却不会调用该方法,而是调用下面的deleteSurroundingText()方法。
* 网上说少数低端手机,无法响应退格键删除功能,后期找华为p9手机,安装搜狗输入法测试
* @param event event事件
* @return
*/
@Override
public boolean sendKeyEvent(KeyEvent event) {
HyperLogUtils.d("DeletableEditText---sendKeyEvent--");
if( event.getKeyCode() == KeyEvent.KEYCODE_DEL && event.getAction() == KeyEvent.ACTION_DOWN){
if(mBackspaceListener != null && mBackspaceListener.onBackspace()){
return true;
}
}
return super.sendKeyEvent(event);
}
/**
* 删除操作
* 有文本删除操作时(剪切,点击退格键),会触发该方法
* @param beforeLength beforeLength
* @param afterLength afterLength
* @return
*/
@Override
public boolean deleteSurroundingText(int beforeLength, int afterLength) {
HyperLogUtils.d("DeletableEditText---deleteSurroundingText--"+beforeLength+"----"+afterLength);
if (beforeLength == 1 && afterLength == 0) {
return sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL))
&& sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL));
}
return super.deleteSurroundingText(beforeLength, afterLength);
}
/**
*结 束组合文本输入的时候,回调该方法
* @return
*/
@Override
public boolean finishComposingText() {
return super.finishComposingText();
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
YCCustomTextLib/src/main/java/com/ns/yc/yccustomtextlib/utils/HyperHtmlUtils.java | Java | package com.ns.yc.yccustomtextlib.utils;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2019/07/18
* desc : 将富文本转化成html格式工具类
* revise: 上传服务器数据:第一种json方式,第二种html方法
* </pre>
*/
public final class HyperHtmlUtils {
/**
* 将字符串格式化成JSON的格式
* @param strJson 字符串
* @return json
*/
public static String stringToJson(String strJson) {
// 计数tab的个数
int tabNum = 0;
StringBuilder jsonFormat = new StringBuilder();
int length = strJson.length();
char last = 0;
for (int i = 0; i < length; i++) {
char c = strJson.charAt(i);
if (c == '{') {
tabNum++;
jsonFormat.append(c).append("\n");
jsonFormat.append(getSpaceOrTab(tabNum));
}
else if (c == '}') {
tabNum--;
jsonFormat.append("\n");
jsonFormat.append(getSpaceOrTab(tabNum));
jsonFormat.append(c);
}
else if (c == ',') {
jsonFormat.append(c).append("\n");
jsonFormat.append(getSpaceOrTab(tabNum));
}
else if (c == ':') {
jsonFormat.append(c).append(" ");
} else if (c == '[') {
tabNum++;
char next = strJson.charAt(i + 1);
if (next == ']') {
jsonFormat.append(c);
}
else {
jsonFormat.append(c).append("\n");
jsonFormat.append(getSpaceOrTab(tabNum));
}
} else if (c == ']') {
tabNum--;
if (last == '[') {
jsonFormat.append(c);
}
else {
jsonFormat.append("\n").append(getSpaceOrTab(tabNum)).append(c);
}
}
else {
jsonFormat.append(c);
}
last = c;
}
return jsonFormat.toString();
}
/**
* 换行操作
* @param tabNum tabNum
* @return
*/
private static String getSpaceOrTab(int tabNum) {
StringBuilder sbTab = new StringBuilder();
for (int i = 0; i < tabNum; i++) {
sbTab.append('\t');
}
return sbTab.toString();
}
/**
* 将内容转化为html格式
* @param content 内容
* @return
*/
public static String stringToHtml(String content){
return null;
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
YCCustomTextLib/src/main/java/com/ns/yc/yccustomtextlib/utils/HyperLibUtils.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
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.
*/
package com.ns.yc.yccustomtextlib.utils;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.ParcelFileDescriptor;
import android.os.ResultReceiver;
import android.support.annotation.NonNull;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.CharacterStyle;
import android.text.style.ForegroundColorSpan;
import android.util.Base64;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2019/07/18
* desc : 功能工具类
* revise:
* </pre>
*/
public final class HyperLibUtils {
private static final String IMG_REGEX1 = "<img.*?src=\\\"(.*?)\\\".*?>";
private static final String IMG_REGEX2 = "<(img|IMG)(.*?)(/>|></img>|>)";
private static final String IMG_REGEX3 = "(src|SRC)=(\"|\')(.*?)(\"|\')";
/**
* dp转化为px
* @param context 上下文
* @param dipValue dp值
* @return
*/
public static int dip2px(Context context, float dipValue) {
float m = context.getResources().getDisplayMetrics().density;
return (int) (dipValue * m + 0.5f);
}
/**
* 关键字高亮显示
* @param target 需要高亮的关键字
* @param text 需要显示的文字
* @return spannable
*/
public static SpannableStringBuilder highlight(String text, String target, int color) {
SpannableStringBuilder spannable = new SpannableStringBuilder(text);
CharacterStyle span;
try {
//将给定的正则表达式编译成模式
Pattern p = Pattern.compile(target);
//创建将根据此模式匹配给定输入的匹配器
Matcher m = p.matcher(text);
while (m.find()) {
// 需要重复!
span = new ForegroundColorSpan(color);
spannable.setSpan(span, m.start(), m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
} catch (Exception e) {
e.printStackTrace();
}
return spannable;
}
/**
* 根据img标签分割出图片和字符串
* @param targetStr 要处理的字符串
* @description 切割字符串,将文本和img标签碎片化,如"ab<img>cd"转换为"ab"、"<img>"、"cd"
*/
public static List<String> cutStringByImgTag(String targetStr) {
List<String> splitTextList = new ArrayList<>();
//将给定的正则表达式编译成模式
Pattern pattern = Pattern.compile(IMG_REGEX1);
//创建将根据此模式匹配给定输入的匹配器
Matcher matcher = pattern.matcher(targetStr);
int lastIndex = 0;
while (matcher.find()) {
if (matcher.start() > lastIndex) {
splitTextList.add(targetStr.substring(lastIndex, matcher.start()));
}
splitTextList.add(targetStr.substring(matcher.start(), matcher.end()));
lastIndex = matcher.end();
}
if (lastIndex != targetStr.length()) {
splitTextList.add(targetStr.substring(lastIndex));
}
return splitTextList;
}
/**
* 获取img标签中的src值
* @param content 内容
* @return
*/
public static String getImgSrc(String content){
String strSrc = null;
//目前img标签标示有3种表达式
//<img alt="" src="1.jpg"/> <img alt="" src="1.jpg"></img> <img alt="" src="1.jpg">
//开始匹配content中的<img />标签
//将给定的正则表达式编译成模式
Pattern pImg = Pattern.compile(IMG_REGEX2);
//创建将根据此模式匹配给定输入的匹配器
Matcher mImg = pImg.matcher(content);
boolean resultImg = mImg.find();
if (resultImg) {
while (resultImg) {
//获取到匹配的<img />标签中的内容
String strImg = mImg.group(2);
//开始匹配<img />标签中的src
Pattern pSrc = Pattern.compile(IMG_REGEX3);
Matcher mSrc = pSrc.matcher(strImg);
if (mSrc.find()) {
strSrc = mSrc.group(3);
}
//结束匹配<img />标签中的src
//匹配content中是否存在下一个<img />标签,有则继续以上步骤匹配<img />标签中的src
resultImg = mImg.find();
}
}
return strSrc;
}
/**
* 从html文本中提取图片地址,或者文本内容
* @param html 传入html文本
* @param isGetImage true获取图片,false获取文本
* @return
*/
public static ArrayList<String> getTextFromHtml(String html, boolean isGetImage){
ArrayList<String> imageList = new ArrayList<>();
ArrayList<String> textList = new ArrayList<>();
//根据img标签分割出图片和字符串
List<String> list = cutStringByImgTag(html);
for (int i = 0; i < list.size(); i++) {
String text = list.get(i);
if (text.contains("<img") && text.contains("src=")) {
//从img标签中获取图片地址
String imagePath = getImgSrc(text);
imageList.add(imagePath);
} else {
textList.add(text);
}
}
//判断是获取图片还是文本
if (isGetImage) {
return imageList;
} else {
return textList;
}
}
/**
* 根据路径获得突破并压缩返回bitmap用于显示
* @param filePath 文件路径
* @param newWidth 宽
* @param newHeight 高
* @return
*/
public static Bitmap getSmallBitmap(String filePath, int newWidth, int newHeight) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap decodeFile = BitmapFactory.decodeFile(filePath, options);
HyperLogUtils.d("HyperLibUtils----getSmallBitmap---byteCount压缩前大小--"+decodeFile);
// Calculate inSampleSize
// 计算图片的缩放值
options.inSampleSize = calculateInSampleSize(options, newWidth, newHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
int bitmapByteCount = bitmap.getByteCount();
HyperLogUtils.d("HyperLibUtils----getSmallBitmap---byteCount压缩中大小--"+bitmapByteCount);
// 质量压缩
Bitmap newBitmap = compressImage(bitmap, 500);
int byteCount = newBitmap.getByteCount();
HyperLogUtils.d("HyperLibUtils----getSmallBitmap---byteCount压缩后大小--"+byteCount);
if (bitmap != null){
// 手动释放资源
bitmap.recycle();
}
return newBitmap;
}
/**
* 计算图片的缩放值
* @param options 属性
* @param reqWidth 宽
* @param reqHeight 高
* @return
*/
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and
// width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will
// guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
/**
* 质量压缩
* @param image bitmap
* @param maxSize 最大值
* @return
*/
public static Bitmap compressImage(Bitmap image, int maxSize){
ByteArrayOutputStream os = new ByteArrayOutputStream();
// scale
int options = 80;
// Store the bitmap into output stream(no compress)
image.compress(Bitmap.CompressFormat.JPEG, options, os);
// Compress by loop
while ( os.toByteArray().length / 1024 > maxSize) {
// Clean up os
os.reset();
// interval 10
options -= 10;
image.compress(Bitmap.CompressFormat.JPEG, options, os);
}
Bitmap bitmap = null;
byte[] b = os.toByteArray();
if (b.length != 0) {
bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
}
return bitmap;
}
/**
* 通过像素压缩图片,将修改图片宽高,适合获得缩略图,Used to get thumbnail
* @param srcPath 图片路径
* @param pixelW 宽
* @param pixelH 高
* @return
*/
public static Bitmap compressBitmapByPath(String srcPath, float pixelW, float pixelH) {
BitmapFactory.Options newOpts = new BitmapFactory.Options();
//开始读入图片,此时把options.inJustDecodeBounds 设回true了
newOpts.inJustDecodeBounds = true;
newOpts.inPreferredConfig = Bitmap.Config.RGB_565;
//此时返回bm为空
Bitmap bitmap = BitmapFactory.decodeFile(srcPath,newOpts);
newOpts.inJustDecodeBounds = false;
int w = newOpts.outWidth;
int h = newOpts.outHeight;
//现在主流手机比较多是800*480分辨率,所以高和宽我们设置为
//这里设置高度为800f
float hh = pixelH;
//这里设置宽度为480f
float ww = pixelW;
//缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
//be=1表示不缩放
int be = 1;
//如果宽度大的话根据宽度固定大小缩放
if (w > h && w > ww) {
be = (int) (newOpts.outWidth / ww);
} else if (w < h && h > hh) {
//如果高度高的话根据宽度固定大小缩放
be = (int) (newOpts.outHeight / hh);
}
if (be <= 0) {
be = 1;
}
//设置缩放比例
newOpts.inSampleSize = be;
//重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
//return compress(bitmap, maxSize); // 这里再进行质量压缩的意义不大,反而耗资源,删除
return bitmap;
}
/**
* 通过大小压缩,将修改图片宽高,适合获得缩略图,Used to get thumbnail
* @param image 图片
* @param pixelW 宽
* @param pixelH 高
* @return
*/
public static Bitmap compressBitmapByBmp(Bitmap image, float pixelW, float pixelH) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, os);
if( os.toByteArray().length / 1024>1024) {
//判断如果图片大于1M,进行压缩避免在生成图片(BitmapFactory.decodeStream)时溢出
os.reset();
//重置baos即清空baos
image.compress(Bitmap.CompressFormat.JPEG, 50, os);
//这里压缩50%,把压缩后的数据存放到baos中
}
ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
BitmapFactory.Options newOpts = new BitmapFactory.Options();
//开始读入图片,此时把options.inJustDecodeBounds 设回true了
newOpts.inJustDecodeBounds = true;
newOpts.inPreferredConfig = Bitmap.Config.RGB_565;
Bitmap bitmap = BitmapFactory.decodeStream(is, null, newOpts);
newOpts.inJustDecodeBounds = false;
int w = newOpts.outWidth;
int h = newOpts.outHeight;
// 设置高度为240f时,可以明显看到图片缩小了
float hh = pixelH;
// 设置宽度为120f,可以明显看到图片缩小了
float ww = pixelW;
//缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
//be=1表示不缩放
int be = 1;
if (w > h && w > ww) {
//如果宽度大的话根据宽度固定大小缩放
be = (int) (newOpts.outWidth / ww);
} else if (w < h && h > hh) {
//如果高度高的话根据宽度固定大小缩放
be = (int) (newOpts.outHeight / hh);
}
if (be <= 0) {
be = 1;
}
//设置缩放比例
newOpts.inSampleSize = be;
//重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
is = new ByteArrayInputStream(os.toByteArray());
bitmap = BitmapFactory.decodeStream(is, null, newOpts);
int desWidth = (int) (w / be);
int desHeight = (int) (h / be);
bitmap = Bitmap.createScaledBitmap(bitmap, desWidth, desHeight, true);
//压缩好比例大小后再进行质量压缩
//return compress(bitmap, maxSize); // 这里再进行质量压缩的意义不大,反而耗资源,删除
return bitmap;
}
/**
* 根据Uri获取真实的文件路径
* @param context 上下文
* @param uri 图片uri地址
* @return
*/
public static String getFilePathFromUri(Context context, Uri uri) {
if (uri == null) {
return null;
}
ContentResolver resolver = context.getContentResolver();
FileInputStream input = null;
FileOutputStream output = null;
try {
ParcelFileDescriptor pfd = resolver.openFileDescriptor(uri, "r");
if (pfd == null) {
return null;
}
FileDescriptor fd = pfd.getFileDescriptor();
input = new FileInputStream(fd);
File outputDir = context.getCacheDir();
File outputFile = File.createTempFile("image", "tmp", outputDir);
String tempFilename = outputFile.getAbsolutePath();
output = new FileOutputStream(tempFilename);
int read;
byte[] bytes = new byte[4096];
while ((read = input.read(bytes)) != -1) {
output.write(bytes, 0, read);
}
return new File(tempFilename).getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (input != null){
input.close();
}
if (output != null){
output.close();
}
} catch (Throwable t) {
// Do nothing
t.printStackTrace();
}
}
return null;
}
public static String toBase64(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] bytes = baos.toByteArray();
return Base64.encodeToString(bytes, Base64.NO_WRAP);
}
public static Bitmap toBitmap(Drawable drawable) {
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
}
int width = drawable.getIntrinsicWidth();
width = width > 0 ? width : 1;
int height = drawable.getIntrinsicHeight();
height = height > 0 ? height : 1;
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
public static Bitmap decodeResource(Context context, int resId) {
return BitmapFactory.decodeResource(context.getResources(), resId);
}
public static long getCurrentTime() {
return System.currentTimeMillis();
}
private static int sDecorViewDelta = 0;
/**
* 判断软键盘是否可见
* @param activity activity上下文
* @return
*/
public static boolean isSoftInputVisible(@NonNull final Activity activity) {
return getDecorViewInvisibleHeight(activity) > 0;
}
/**
* 获取DecorView可见的高度
* @param activity activity
* @return
*/
private static int getDecorViewInvisibleHeight(final Activity activity) {
Window window = activity.getWindow();
if (window==null){
return 0;
}
final View decorView = window.getDecorView();
final Rect outRect = new Rect();
decorView.getWindowVisibleDisplayFrame(outRect);
HyperLogUtils.d("getDecorViewInvisibleHeight: " + (decorView.getBottom() - outRect.bottom));
int delta = Math.abs(decorView.getBottom() - outRect.bottom);
if (delta <= getNavBarHeight(activity) + getStatusBarHeight(activity)) {
sDecorViewDelta = delta;
return 0;
}
return delta - sDecorViewDelta;
}
/**
* 获取状态栏高度
* @return
*/
private static int getStatusBarHeight(Context context) {
Resources resources = context.getApplicationContext().getResources();
int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
return resources.getDimensionPixelSize(resourceId);
}
/**
* 获取底部导航栏高度
* @return
*/
private static int getNavBarHeight(Context context) {
Resources res = context.getApplicationContext().getResources();
int resourceId = res.getIdentifier("navigation_bar_height", "dimen", "android");
if (resourceId != 0) {
return res.getDimensionPixelSize(resourceId);
} else {
return 0;
}
}
/**
* 隐藏软键盘
* @param activity 上下文
*/
public static void hideSoftInput(@NonNull final Activity activity) {
View view = activity.getCurrentFocus();
if (view == null) {
View decorView = activity.getWindow().getDecorView();
View focusView = decorView.findViewWithTag("keyboardTagView");
if (focusView == null) {
view = new EditText(activity);
view.setTag("keyboardTagView");
((ViewGroup) decorView).addView(view, 0, 0);
} else {
view = focusView;
}
view.requestFocus();
}
hideSoftInput(activity,view);
}
/**
* 隐藏软键盘
* @param context 上下文
* @param view view
*/
public static void hideSoftInput(Context context, @NonNull final View view) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm == null) {
return;
}
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
//imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
//imm.hideSoftInputFromInputMethod();//据说无效
//imm.hideSoftInputFromWindow(et_content.getWindowToken(), 0); //强制隐藏键盘
//如果输入法在窗口上已经显示,则隐藏,反之则显示
//imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
}
/**
* 打开软键盘
* @param activity 上下文
*/
public static void openSoftInput(@NonNull Activity activity) {
if (!isSoftInputVisible(activity)) {
toggleSoftInput(activity);
}
}
/**
* 打开软键盘
* @param activity 上下文
* @param view view
*/
public static void openSoftInput(Activity activity, final View view) {
openSoftInput(activity,view, 0);
}
/**
* 打开软键盘
* @param context 上下文
* @param view view
* @param flags flags
*/
private static void openSoftInput(final Context context, @NonNull final View view, final int flags) {
InputMethodManager imm = (InputMethodManager) context.getApplicationContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm == null) {
return;
}
view.setFocusable(true);
view.setFocusableInTouchMode(true);
view.requestFocus();
imm.showSoftInput(view, flags, new ResultReceiver(new Handler()) {
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
if (resultCode == InputMethodManager.RESULT_UNCHANGED_HIDDEN
|| resultCode == InputMethodManager.RESULT_HIDDEN) {
toggleSoftInput(context);
}
}
});
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
}
private static void toggleSoftInput(Context context) {
InputMethodManager imm = (InputMethodManager) context.getApplicationContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm == null) {
return;
}
imm.toggleSoftInput(0, 0);
}
/**
* 代码设置光标颜色
*
* @param editText 你使用的EditText
* @param color 光标颜色
*/
public static void setCursorDrawableColor(EditText editText, int color) {
if (editText==null){
return;
}
try {
//获取这个字段
Field fCursorDrawableRes = TextView.class.getDeclaredField("mCursorDrawableRes");
//代表这个字段、方法等等可以被访问
fCursorDrawableRes.setAccessible(true);
int mCursorDrawableRes = fCursorDrawableRes.getInt(editText);
Field fEditor = TextView.class.getDeclaredField("mEditor");
fEditor.setAccessible(true);
Object editor = fEditor.get(editText);
Class<?> clazz = editor.getClass();
Field fCursorDrawable = clazz.getDeclaredField("mCursorDrawable");
fCursorDrawable.setAccessible(true);
Drawable[] drawables = new Drawable[2];
drawables[0] = editText.getContext().getResources().getDrawable(mCursorDrawableRes);
drawables[1] = editText.getContext().getResources().getDrawable(mCursorDrawableRes);
//SRC_IN 上下层都显示。下层居上显示。
drawables[0].setColorFilter(color, PorterDuff.Mode.SRC_IN);
drawables[1].setColorFilter(color, PorterDuff.Mode.SRC_IN);
fCursorDrawable.set(editor, drawables);
} catch (Resources.NotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
YCCustomTextLib/src/main/java/com/ns/yc/yccustomtextlib/utils/HyperLogUtils.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
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.
*/
package com.ns.yc.yccustomtextlib.utils;
import android.util.Log;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2019/07/18
* desc : 日志工具类
* revise:
* </pre>
*/
public final class HyperLogUtils {
private static final String TAG = "HyperLogUtils";
private static boolean isLog = true;
/**
* 设置是否开启日志
* @param isLog 是否开启日志
*/
public static void setIsLog(boolean isLog) {
HyperLogUtils.isLog = isLog;
}
public static void d(String message) {
if(isLog){
Log.d(TAG, message);
}
}
public static void i(String message) {
if(isLog){
Log.i(TAG, message);
}
}
public static void e(String message, Throwable throwable) {
if(isLog){
Log.e(TAG, message, throwable);
}
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
YCCustomTextLib/src/main/java/com/ns/yc/yccustomtextlib/web/AfterInitialLoadListener.java | Java | package com.ns.yc.yccustomtextlib.web;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2019/07/18
* desc : 加载结束监听
* revise:
* </pre>
*/
public interface AfterInitialLoadListener {
/**
* 加载结束监听
* @param isReady 是否结束
*/
void onAfterInitialLoad(boolean isReady);
} | yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
YCCustomTextLib/src/main/java/com/ns/yc/yccustomtextlib/web/OnDecorationListener.java | Java | package com.ns.yc.yccustomtextlib.web;
import java.util.List;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2019/07/18
* desc : 状态变化监听
* revise:
* </pre>
*/
public interface OnDecorationListener {
/**
* 状态变化监听事件
* @param text 文字内容
* @param types 类型
*/
void onStateChangeListener(String text, List<WebRichType> types);
} | yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
YCCustomTextLib/src/main/java/com/ns/yc/yccustomtextlib/web/OnTextChangeListener.java | Java | package com.ns.yc.yccustomtextlib.web;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2019/07/18
* desc : 文本内容变化监听
* revise:
* </pre>
*/
public interface OnTextChangeListener {
/**
* 内容变化监听
* @param text 内容
*/
void onTextChange(String text);
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
YCCustomTextLib/src/main/java/com/ns/yc/yccustomtextlib/web/WebRichType.java | Java | package com.ns.yc.yccustomtextlib.web;
public enum WebRichType {
/**
* 加粗
*/
BOLD,
ITALIC,
SUBSCRIPT,
SUPERSCRIPT,
STRIKETHROUGH,
UNDERLINE,
H1,
H2,
H3,
H4,
H5,
H6,
ORDEREDLIST,
UNORDEREDLIST,
JUSTIFYCENTER,
JUSTIFYFULL,
JUSTUFYLEFT,
JUSTIFYRIGHT
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
YCCustomTextLib/src/main/java/com/ns/yc/yccustomtextlib/web/WebViewRichEditor.java | Java | package com.ns.yc.yccustomtextlib.web;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.ns.yc.yccustomtextlib.utils.HyperLibUtils;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2019/07/18
* desc : 自定义WebView富文本控件
* revise: 遇到问题,webView如何设置图片点击去除功能,如何剧中裁剪功能
* </pre>
*/
public class WebViewRichEditor extends WebView {
private static final String SETUP_HTML = "file:///android_asset/editor.html";
private static final String CALLBACK_SCHEME = "re-callback://";
private static final String STATE_SCHEME = "re-state://";
private boolean isReady = false;
private String mContents;
private OnTextChangeListener mTextChangeListener;
private OnDecorationListener mDecorationStateListener;
private AfterInitialLoadListener mLoadListener;
public WebViewRichEditor(Context context) {
this(context, null);
}
public WebViewRichEditor(Context context, AttributeSet attrs) {
this(context, attrs, android.R.attr.webViewStyle);
}
@SuppressLint("SetJavaScriptEnabled")
public WebViewRichEditor(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setVerticalScrollBarEnabled(false);
setHorizontalScrollBarEnabled(false);
getSettings().setJavaScriptEnabled(true);
setWebChromeClient(new WebChromeClient());
setWebViewClient(new EditorWebViewClient());
loadUrl(SETUP_HTML);
applyAttributes(context, attrs);
}
public void setOnTextChangeListener(OnTextChangeListener listener) {
mTextChangeListener = listener;
}
public void setOnDecorationChangeListener(OnDecorationListener listener) {
mDecorationStateListener = listener;
}
public void setOnInitialLoadListener(AfterInitialLoadListener listener) {
mLoadListener = listener;
}
private void callback(String text) {
mContents = text.replaceFirst(CALLBACK_SCHEME, "");
if (mTextChangeListener != null) {
mTextChangeListener.onTextChange(mContents);
}
}
private void stateCheck(String text) {
String state = text.replaceFirst(STATE_SCHEME, "").toUpperCase(Locale.ENGLISH);
List<WebRichType> types = new ArrayList<>();
for (WebRichType type : WebRichType.values()) {
if (TextUtils.indexOf(state, type.name()) != -1) {
types.add(type);
}
}
if (mDecorationStateListener != null) {
mDecorationStateListener.onStateChangeListener(state, types);
}
}
private void applyAttributes(Context context, AttributeSet attrs) {
final int[] attrsArray = new int[]{android.R.attr.gravity};
TypedArray ta = context.obtainStyledAttributes(attrs, attrsArray);
int gravity = ta.getInt(0, NO_ID);
switch (gravity) {
case Gravity.START:
case Gravity.LEFT:
exec("javascript:RE.setTextAlign(\"left\")");
break;
case Gravity.END:
case Gravity.RIGHT:
exec("javascript:RE.setTextAlign(\"right\")");
break;
case Gravity.TOP:
exec("javascript:RE.setVerticalAlign(\"top\")");
break;
case Gravity.BOTTOM:
exec("javascript:RE.setVerticalAlign(\"bottom\")");
break;
case Gravity.CENTER_VERTICAL:
exec("javascript:RE.setVerticalAlign(\"middle\")");
break;
case Gravity.CENTER_HORIZONTAL:
exec("javascript:RE.setTextAlign(\"center\")");
break;
case Gravity.CENTER:
exec("javascript:RE.setVerticalAlign(\"middle\")");
exec("javascript:RE.setTextAlign(\"center\")");
break;
default:
break;
}
ta.recycle();
}
public void setHtml(String contents) {
if (contents == null) {
contents = "";
}
try {
exec("javascript:RE.setHtml('" + URLEncoder.encode(contents, "UTF-8") + "');");
} catch (UnsupportedEncodingException e) {
// No handling
}
mContents = contents;
}
public String getHtml() {
return mContents;
}
public void setEditorFontColor(int color) {
String hex = convertHexColorString(color);
exec("javascript:RE.setBaseTextColor('" + hex + "');");
}
public void setEditorFontSize(int px) {
exec("javascript:RE.setBaseFontSize('" + px + "px');");
}
@Override
public void setPadding(int left, int top, int right, int bottom) {
super.setPadding(left, top, right, bottom);
exec("javascript:RE.setPadding('" + left + "px', '" + top + "px', '" + right + "px', '" + bottom + "px');");
}
@Override
public void setPaddingRelative(int start, int top, int end, int bottom) {
// still not support RTL.
setPadding(start, top, end, bottom);
}
public void setEditorBackgroundColor(int color) {
setBackgroundColor(color);
}
@Override
public void setBackgroundColor(int color) {
super.setBackgroundColor(color);
}
@Override
public void setBackgroundResource(int resid) {
Bitmap bitmap = HyperLibUtils.decodeResource(getContext(), resid);
String base64 = HyperLibUtils.toBase64(bitmap);
bitmap.recycle();
exec("javascript:RE.setBackgroundImage('url(data:image/png;base64," + base64 + ")');");
}
@Override
public void setBackground(Drawable background) {
Bitmap bitmap = HyperLibUtils.toBitmap(background);
String base64 = HyperLibUtils.toBase64(bitmap);
bitmap.recycle();
exec("javascript:RE.setBackgroundImage('url(data:image/png;base64," + base64 + ")');");
}
public void setBackground(String url) {
exec("javascript:RE.setBackgroundImage('url(" + url + ")');");
}
public void setEditorWidth(int px) {
exec("javascript:RE.setWidth('" + px + "px');");
}
public void setEditorHeight(int px) {
exec("javascript:RE.setHeight('" + px + "px');");
}
public void setPlaceholder(String placeholder) {
exec("javascript:RE.setPlaceholder('" + placeholder + "');");
}
public void setInputEnabled(Boolean inputEnabled) {
exec("javascript:RE.setInputEnabled(" + inputEnabled + ")");
}
public void loadCSS(String cssFile) {
String jsCSSImport = "(function() {" +
" var head = document.getElementsByTagName(\"head\")[0];" +
" var link = document.createElement(\"link\");" +
" link.rel = \"stylesheet\";" +
" link.type = \"text/css\";" +
" link.href = \"" + cssFile + "\";" +
" link.media = \"all\";" +
" head.appendChild(link);" +
"}) ();";
exec("javascript:" + jsCSSImport + "");
}
public void undo() {
exec("javascript:RE.undo();");
}
public void redo() {
exec("javascript:RE.redo();");
}
public void setBold() {
exec("javascript:RE.setBold();");
}
public void setItalic() {
exec("javascript:RE.setItalic();");
}
public void setSubscript() {
exec("javascript:RE.setSubscript();");
}
public void setSuperscript() {
exec("javascript:RE.setSuperscript();");
}
public void setStrikeThrough() {
exec("javascript:RE.setStrikeThrough();");
}
public void setUnderline() {
exec("javascript:RE.setUnderline();");
}
public void setTextColor(int color) {
exec("javascript:RE.prepareInsert();");
String hex = convertHexColorString(color);
exec("javascript:RE.setTextColor('" + hex + "');");
}
public void setTextBackgroundColor(int color) {
exec("javascript:RE.prepareInsert();");
String hex = convertHexColorString(color);
exec("javascript:RE.setTextBackgroundColor('" + hex + "');");
}
public void setFontSize(int fontSize) {
if (fontSize > 7 || fontSize < 1) {
Log.e("RichEditor", "Font size should have a value between 1-7");
}
exec("javascript:RE.setFontSize('" + fontSize + "');");
}
public void removeFormat() {
exec("javascript:RE.removeFormat();");
}
public void setHeading(int heading) {
exec("javascript:RE.setHeading('" + heading + "');");
}
public void setIndent() {
exec("javascript:RE.setIndent();");
}
public void setOutdent() {
exec("javascript:RE.setOutdent();");
}
public void setAlignLeft() {
exec("javascript:RE.setJustifyLeft();");
}
public void setAlignCenter() {
exec("javascript:RE.setJustifyCenter();");
}
public void setAlignRight() {
exec("javascript:RE.setJustifyRight();");
}
public void setBlockquote() {
exec("javascript:RE.setBlockquote();");
}
public void setBullets() {
exec("javascript:RE.setBullets();");
}
public void setNumbers() {
exec("javascript:RE.setNumbers();");
}
public void insertImage(String url, String alt) {
exec("javascript:RE.prepareInsert();");
exec("javascript:RE.insertImage('" + url + "', '" + alt + "');");
}
public void insertLink(String href, String title) {
exec("javascript:RE.prepareInsert();");
exec("javascript:RE.insertLink('" + href + "', '" + title + "');");
}
public void insertTodo() {
exec("javascript:RE.prepareInsert();");
exec("javascript:RE.setTodo('" + HyperLibUtils.getCurrentTime() + "');");
}
public void focusEditor() {
requestFocus();
exec("javascript:RE.focus();");
}
public void clearFocusEditor() {
exec("javascript:RE.blurFocus();");
}
private String convertHexColorString(int color) {
return String.format("#%06X", (0xFFFFFF & color));
}
protected void exec(final String trigger) {
if (isReady) {
load(trigger);
} else {
postDelayed(new Runnable() {
@Override
public void run() {
exec(trigger);
}
}, 100);
}
}
/**
* 4.4以上可用 evaluateJavascript
* @param trigger trigger
*/
private void load(String trigger) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
evaluateJavascript(trigger, null);
} else {
loadUrl(trigger);
}
}
protected class EditorWebViewClient extends WebViewClient {
@Override
public void onPageFinished(WebView view, String url) {
isReady = url.equalsIgnoreCase(SETUP_HTML);
if (mLoadListener != null) {
mLoadListener.onAfterInitialLoad(isReady);
}
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
String decode;
try {
decode = URLDecoder.decode(url, "UTF-8");
} catch (UnsupportedEncodingException e) {
// No handling
return false;
}
if (TextUtils.indexOf(url, CALLBACK_SCHEME) == 0) {
callback(decode);
return true;
} else if (TextUtils.indexOf(url, STATE_SCHEME) == 0) {
stateCheck(decode);
return true;
}
return super.shouldOverrideUrlLoading(view, url);
}
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
app/build.gradle | Gradle | apply plugin: 'com.android.application'
android {
compileSdkVersion 28
buildToolsVersion "27.0.3"
defaultConfig {
applicationId "com.ns.yc.yccustomtext"
minSdkVersion 17
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support:cardview-v7:28.0.0'
implementation project(':YCCustomTextLib')
// implementation 'cn.yc:YCCustomTextLib:2.1.4'
implementation 'cn.yc:YCStatusBarLib:1.5.0'
implementation 'cn.yc:YCDialogLib:3.6.6'
implementation 'com.github.tbruyelle:rxpermissions:0.10.2'
implementation 'com.github.bumptech.glide:glide:4.9.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'
implementation 'com.github.bumptech.glide:okhttp3-integration:4.9.0'
// implementation 'io.reactivex:rxjava:1.1.0'
// implementation 'io.reactivex:rxandroid:1.1.0'
implementation 'com.zhihu.android:matisse:0.5.2-beta4'
implementation 'com.google.code.gson:gson:2.8.5'
implementation "io.reactivex.rxjava2:rxjava:2.2.3"
implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'
implementation 'com.github.iielse:ImageWatcher:1.1.5'
implementation project(path: ':SuperTextLib')
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
app/src/androidTest/java/com/ns/yc/yccustomtext/ExampleInstrumentedTest.java | Java | package com.ns.yc.yccustomtext;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.ns.yc.yccustomtext", appContext.getPackageName());
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
app/src/main/java/com/ns/yc/yccustomtext/AlignActivity.java | Java | package com.ns.yc.yccustomtext;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import com.yc.supertextlib.AlignTextView;
import com.yc.supertextlib.BalanceTextView;
public class AlignActivity extends AppCompatActivity {
private TextView mTv0;
private AlignTextView mTvAlign0;
private BalanceTextView mTvSuper0;
private TextView mTv1;
private AlignTextView mTvAlign1;
private BalanceTextView mTvSuper1;
private TextView mTv2;
private AlignTextView mTvAlign2;
private BalanceTextView mTvSuper3;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_align_text);
mTv0 = findViewById(R.id.tv_0);
mTvAlign0 = findViewById(R.id.tv_align_0);
mTvSuper0 = findViewById(R.id.tv_super_0);
mTv1 = findViewById(R.id.tv_1);
mTvAlign1 = findViewById(R.id.tv_align_1);
mTvSuper1 = findViewById(R.id.tv_super_1);
mTv2 = findViewById(R.id.tv_2);
mTvAlign2 = findViewById(R.id.tv_align_2);
mTvSuper3 = findViewById(R.id.tv_super_3);
mTv0.setText(getResources().getString(R.string.content0));
mTvAlign0.setText(getResources().getString(R.string.content0));
mTvSuper0.setText(getResources().getString(R.string.content0));
mTv1.setText(getResources().getString(R.string.content1));
mTvAlign1.setText(getResources().getString(R.string.content1));
mTvSuper1.setText(getResources().getString(R.string.content1));
mTv2.setText(getResources().getString(R.string.content2));
mTvAlign2.setText(getResources().getString(R.string.content2));
mTvSuper3.setText(getResources().getString(R.string.content2));
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
app/src/main/java/com/ns/yc/yccustomtext/ColorPickerView.java | Java | package com.ns.yc.yccustomtext;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
/**
* <p>
* 指示点的半径是颜色条宽度的 4/3 ,两端会有指示点半径长的距离是空白的,这是为了给指示点滑动到端点时留出足够的显示空间,
* 这也导致当控件宽高的差值太小时,指示点会完全覆盖住颜色条,使颜色条不可见,<strong>因此应尽量根据控件的不同模式使长
* 边与段边的比例不小于 3 : 1</strong>
* <br>
* <p>
* 两种模式:
* <p>
* HORIZONTAL 水平
* <p>
* VERTICAL 竖直
*/
public class ColorPickerView extends View {
/**
* 指示点颜色
*/
private int mIndicatorColor;
/**
* 是否启用指示点
*/
private boolean mIndicatorEnable;
/**
* View 和 bitmapForColor 的画笔
*/
private final Paint paint;
/**
* 指示点专用画笔,这样可以避免 mIndicatorColor 有 alpha 时,alpha 作用于 View
*/
private final Paint paintForIndicator;
private LinearGradient linearGradient;
/**
* 除去上下 padding 的端点坐标
*/
private int mTop, mLeft, mRight, mBottom;
/**
* 颜色条圆角矩形边界
*/
private final Rect rect = new Rect();
/**
* bitmapForIndicator 在 View 上的绘制位置
*/
private final Rect rectForIndicator = new Rect();
/**
* 指示点半径
*/
private int mRadius;
/**
* 控件方向
*/
private Orientation orientation;
// 默认状态下长边与短边的比例为 6 :1
private static final int defaultSizeShort = 70; // * 6
private static final int defaultSizeLong = 420;
// 不直接绘制在 View 提供的画布上的原因是:选取颜色时需要提取 Bitmap 上的颜色,View 的 Bitmap 无法获取,
// 而且有指示点时指示点会覆盖主颜色条(重绘颜色条的颜色)
private Bitmap bitmapForColor;
private Bitmap bitmapForIndicator;
/**
* 是否需要绘制颜色条(指示点),颜色条在选取颜色时不需要再次生成(bitmapForColor),直接绘制就行
*/
private boolean needReDrawColorTable = true;
private boolean needReDrawIndicator = true;
/**
* 手指在颜色条上的坐标
*/
private int curX, curY;
private int[] colors = null;
private int currentColor;
/**
* 控件方向
*/
public enum Orientation {
/**
* 水平
*/
HORIZONTAL, // 0
/**
* 竖直
*/
VERTICAL // 1
}
{
bitmapForColor = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
bitmapForIndicator = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
//Android4.0(API14)之后硬件加速功能就被默认开启了,setShadowLayer 在开启硬件加速的情况下无效,需要关闭硬件加速
this.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
paint = new Paint();
paint.setAntiAlias(true);
paintForIndicator = new Paint();
paintForIndicator.setAntiAlias(true);
curX = curY = Integer.MAX_VALUE;
}
public ColorPickerView(Context context) {
super(context);
}
public ColorPickerView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public ColorPickerView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
final TypedArray array = context.getTheme().obtainStyledAttributes(attrs, R.styleable.ColorPickerView, defStyleAttr, 0);
mIndicatorColor = array.getColor(R.styleable.ColorPickerView_indicatorColor, Color.WHITE);
int or = array.getInteger(R.styleable.ColorPickerView_orientation, 0);
orientation = or == 0 ? Orientation.HORIZONTAL : Orientation.VERTICAL;
mIndicatorEnable = array.getBoolean(R.styleable.ColorPickerView_indicatorEnable, true);
array.recycle();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int width;
int height;
if (widthMode == MeasureSpec.EXACTLY) {
width = widthSize;
} else {//xml中宽度设为warp_content
width = getSuggestedMinimumWidth() + getPaddingLeft() + getPaddingRight();
}
if (heightMode == MeasureSpec.EXACTLY) {
height = heightSize;
} else {
height = getSuggestedMinimumHeight() + getPaddingTop() + getPaddingBottom();
}
width = Math.max(width, orientation == Orientation.HORIZONTAL ? defaultSizeLong : defaultSizeShort);
height = Math.max(height, orientation == Orientation.HORIZONTAL ? defaultSizeShort : defaultSizeLong);
setMeasuredDimension(width, height);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
mTop = getPaddingTop();
mLeft = getPaddingLeft();
mBottom = getMeasuredHeight() - getPaddingBottom();
mRight = getMeasuredWidth() - getPaddingRight();
if (curX == curY || curY == Integer.MAX_VALUE) {
curX = getWidth() / 2;
curY = getHeight() / 2;
}
calculBounds();
if (colors == null) {
setColors(createDefaultColorTable());
} else {
setColors(colors);
}
createBitmap();
if (mIndicatorEnable) {
needReDrawIndicator = true;
}
}
private void createBitmap() {
int hc = rect.height();
int wc = rect.width();
int hi = mRadius * 2;
int wi = hi;
if (bitmapForColor != null) {
if (!bitmapForColor.isRecycled()) {
bitmapForColor.recycle();
bitmapForColor = null;
}
}
if (bitmapForIndicator != null) {
if (!bitmapForIndicator.isRecycled()) {
bitmapForIndicator.recycle();
bitmapForIndicator = null;
}
}
bitmapForColor = Bitmap.createBitmap(wc, hc, Bitmap.Config.ARGB_8888);
bitmapForIndicator = Bitmap.createBitmap(wi, hi, Bitmap.Config.ARGB_8888);
}
/**
* 计算颜色条边界
*/
private void calculBounds() {
/*
* 将控件可用高度(除去上下 padding )均分为 6 份,以此计算指示点半径,颜色条宽高
* 控件方向为 HORIZONTAL 时,从上往下依次占的份额为:
* 1/9 留白
* 2/9 颜色条上面部分圆
* 3/9 颜色条宽
* 2/9 颜色条上面部分圆
* 1/9 留白
*/
final int average = 9;
/*
* 每一份的高度
*/
int each;
int h = mBottom - mTop;
int w = mRight - mLeft;
int size = Math.min(w, h);
if (orientation == Orientation.HORIZONTAL) {
if (w <= h) { // HORIZONTAL 模式,然而宽却小于高,以 6 :1 的方式重新计算高
size = w / 6;
}
} else {
if (w >= h) {
size = h / 6;
}
}
each = size / average;
mRadius = each * 7 / 2;
int t, l, b, r;
final int s = each * 3 / 2;
if (orientation == Orientation.HORIZONTAL) {
l = mLeft + mRadius;
r = mRight - mRadius;
t = (getHeight() / 2) - s;
b = (getHeight() / 2) + s;
} else {
t = mTop + mRadius;
b = mBottom - mRadius;
l = getWidth() / 2 - s;
r = getWidth() / 2 + s;
}
rect.set(l, t, r, b);
}
/**
* 设置颜色条的渐变颜色,不支持具有 alpha 的颜色,{@link Color#TRANSPARENT}会被当成 {@link Color#BLACK}处理
* 如果想设置 alpha ,可以在{@link OnColorPickerChangeListener#onColorChanged(ColorPickerView, int)} 回调
* 中调用{@link android.support.v4.graphics.ColorUtils#setAlphaComponent(int, int)}方法添加 alpha 值。
*
* @param colors 颜色值
*/
public void setColors(int... colors) {
linearGradient = null;
this.colors = colors;
if (orientation == Orientation.HORIZONTAL) {
linearGradient = new LinearGradient(
rect.left, rect.top,
rect.right, rect.top,
colors,
null,
Shader.TileMode.CLAMP
);
} else {
linearGradient = new LinearGradient(
rect.left, rect.top,
rect.left, rect.bottom,
colors,
null,
Shader.TileMode.CLAMP
);
}
needReDrawColorTable = true;
invalidate();
}
public int[] createDefaultColorTable() {
// int[] cs = {
// Color.rgb(0, 0, 0),//白色
// Color.rgb(255, 0, 0),//红色
// Color.rgb(0, 255, 0),//绿色
// Color.rgb(0, 255, 255),//青色
// Color.rgb(0, 0, 255),//蓝色
// Color.rgb(255, 0, 255),//紫色
// Color.rgb(255, 255, 255)//黑色
// };
int[] cs = {
Color.rgb(0, 0, 0),
Color.rgb(255, 0, 0),//红色
Color.rgb(255, 255, 0),
Color.rgb(0, 255, 0),//绿色
Color.rgb(0, 255, 255),//青色
Color.rgb(0, 0, 255),//蓝色
Color.rgb(255, 0, 255),
Color.rgb(255, 0, 0)//红色
};
return cs;
}
@Override
protected void onDraw(Canvas canvas) {
if (needReDrawColorTable) {
createColorTableBitmap();
}
// 绘制颜色条
canvas.drawBitmap(bitmapForColor, null, rect, paint);
if (mIndicatorEnable) {
if (needReDrawIndicator) {
createIndicatorBitmap();
}
// 绘制指示点
rectForIndicator.set(curX - mRadius, curY - mRadius, curX + mRadius, curY + mRadius);
canvas.drawBitmap(bitmapForIndicator, null, rectForIndicator, paint);
}
}
private void createIndicatorBitmap() {
paintForIndicator.setColor(mIndicatorColor);
int radius = 3;
paintForIndicator.setShadowLayer(radius, 0, 0, Color.GRAY);
Canvas c = new Canvas(bitmapForIndicator);
c.drawCircle(mRadius, mRadius, mRadius - radius, paintForIndicator);
needReDrawIndicator = false;
}
private void createColorTableBitmap() {
Canvas c = new Canvas(bitmapForColor);
RectF rf = new RectF(0, 0, bitmapForColor.getWidth(), bitmapForColor.getHeight());
// 圆角大小
int r;
if (orientation == Orientation.HORIZONTAL) {
r = bitmapForColor.getHeight() / 2;
} else {
r = bitmapForColor.getWidth() / 2;
}
// 先绘制黑色背景,否则有 alpha 时绘制不正常
paint.setColor(Color.BLACK);
c.drawRoundRect(rf, r, r, paint);
paint.setShader(linearGradient);
c.drawRoundRect(rf, r, r, paint);
paint.setShader(null);
needReDrawColorTable = false;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int ex = (int) event.getX();
int ey = (int) event.getY();
if (!inBoundOfColorTable(ex, ey)) {
return true;
}
if (orientation == Orientation.HORIZONTAL) {
curX = ex;
curY = getHeight() / 2;
} else {
curX = getWidth() / 2;
curY = ey;
}
if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
if (colorPickerChangeListener != null) {
colorPickerChangeListener.onStartTrackingTouch(this);
calcuColor();
colorPickerChangeListener.onColorChanged(this, currentColor);
}
} else if (event.getActionMasked() == MotionEvent.ACTION_UP) { //手抬起
if (colorPickerChangeListener != null) {
colorPickerChangeListener.onStopTrackingTouch(this);
calcuColor();
colorPickerChangeListener.onColorChanged(this, currentColor);
}
} else { //按着+拖拽
if (colorPickerChangeListener != null) {
calcuColor();
colorPickerChangeListener.onColorChanged(this, currentColor);
}
}
invalidate();
return true;
}
/**
* 获得当前指示点所指颜色
*
* @return 颜色值
*/
public int getColor() {
return calcuColor();
}
private boolean inBoundOfColorTable(int ex, int ey) {
if (orientation == Orientation.HORIZONTAL) {
if (ex <= mLeft + mRadius || ex >= mRight - mRadius) {
return false;
}
} else {
if (ey <= mTop + mRadius || ey >= mBottom - mRadius) {
return false;
}
}
return true;
}
private int calcuColor() {
int x, y;
if (orientation == Orientation.HORIZONTAL) { // 水平
y = (rect.bottom - rect.top) / 2;
if (curX < rect.left) {
x = 1;
} else if (curX > rect.right) {
x = bitmapForColor.getWidth() - 1;
} else {
x = curX - rect.left;
}
} else { // 竖直
x = (rect.right - rect.left) / 2;
if (curY < rect.top) {
y = 1;
} else if (curY > rect.bottom) {
y = bitmapForColor.getHeight() - 1;
} else {
y = curY - rect.top;
}
}
int pixel = bitmapForColor.getPixel(x, y);
currentColor = pixelToColor(pixel);
return currentColor;
}
private int pixelToColor(int pixel) {
int alpha = Color.alpha(pixel);
int red = Color.red(pixel);
int green = Color.green(pixel);
int blue = Color.blue(pixel);
return Color.argb(alpha, red, green, blue);
}
private OnColorPickerChangeListener colorPickerChangeListener;
public void setOnColorPickerChangeListener(OnColorPickerChangeListener l) {
this.colorPickerChangeListener = l;
}
public interface OnColorPickerChangeListener {
/**
* 选取的颜色值改变时回调
*
* @param picker ColorPickerView
* @param color 颜色
*/
void onColorChanged(ColorPickerView picker, int color);
/**
* 开始颜色选取
*
* @param picker ColorPickerView
*/
void onStartTrackingTouch(ColorPickerView picker);
/**
* 停止颜色选取
*
* @param picker ColorPickerView
*/
void onStopTrackingTouch(ColorPickerView picker);
}
@Override
protected Parcelable onSaveInstanceState() {
Parcelable parcelable = super.onSaveInstanceState();
SavedState ss = new SavedState(parcelable);
ss.selX = curX;
ss.selY = curY;
ss.color = bitmapForColor;
if (mIndicatorEnable) {
ss.indicator = bitmapForIndicator;
}
return ss;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
if (!(state instanceof SavedState)) {
super.onRestoreInstanceState(state);
return;
}
SavedState ss = (SavedState) state;
super.onRestoreInstanceState(ss.getSuperState());
curX = ss.selX;
curY = ss.selY;
colors = ss.colors;
bitmapForColor = ss.color;
if (mIndicatorEnable) {
bitmapForIndicator = ss.indicator;
needReDrawIndicator = true;
}
needReDrawColorTable = true;
}
private class SavedState extends BaseSavedState {
int selX, selY;
int[] colors;
Bitmap color;
Bitmap indicator = null;
SavedState(Parcelable source) {
super(source);
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeInt(selX);
out.writeInt(selY);
out.writeParcelable(color, flags);
out.writeIntArray(colors);
if (indicator != null) {
out.writeParcelable(indicator, flags);
}
}
}
public void setPosition(int x, int y) {
if (inBoundOfColorTable(x, y)) {
curX = x;
curY = y;
if (mIndicatorEnable) {
needReDrawIndicator = true;
}
invalidate();
}
}
/**
* 显示默认的颜色选择器
*/
public void showDefaultColorTable() {
setColors(createDefaultColorTable());
}
public int getIndicatorColor() {
return mIndicatorColor;
}
public void setIndicatorColor(int color) {
this.mIndicatorColor = color;
needReDrawIndicator = true;
invalidate();
}
public void setOrientation(Orientation orientation) {
this.orientation = orientation;
needReDrawIndicator = true;
needReDrawColorTable = true;
requestLayout();
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
app/src/main/java/com/ns/yc/yccustomtext/CommonUtil.java | Java | package com.ns.yc.yccustomtext;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.PowerManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
* Created by sendtion on 2016/3/30.
*/
public class CommonUtil {
/**
* 判断应用是否处于后台
* @param context
* @return
*/
public static boolean isAppOnBackground(Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
if (!tasks.isEmpty()) {
ComponentName topActivity = tasks.get(0).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
return true;
}
}
return false;
}
/**
* 判断是否锁屏
* @param context
* @return
*/
public static boolean isLockScreeen(Context context){
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
boolean isScreenOn = pm.isScreenOn();//如果为true,则表示屏幕“亮”了,否则屏幕“暗”了。
if (isScreenOn){
return false;
} else {
return true;
}
}
/**
* 分享文字笔记
*/
public static void shareText(Context context, String content){
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT, content);
shareIntent.setType("text/plain");
//设置分享列表的标题,并且每次都显示分享列表
context.startActivity(Intent.createChooser(shareIntent, "分享到"));
}
/**
* 分享单张图片
* @param context
* @param imagePath
*/
public static void shareImage(Context context, String imagePath) {
//String imagePath = Environment.getExternalStorageDirectory() + File.separator + "test.jpg";
Uri imageUri = Uri.fromFile(new File(imagePath));//由文件得到uri
Log.d("share", "uri:" + imageUri); //输出:file:///storage/emulated/0/test.jpg
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
shareIntent.setType("image/*");
context.startActivity(Intent.createChooser(shareIntent, "分享到"));
}
/**
* 分享功能
*
* @param context
* 上下文
* @param msgTitle
* 消息标题
* @param msgText
* 消息内容
* @param imgPath
* 图片路径,不分享图片则传null
*/
public static void shareTextAndImage(Context context, String msgTitle, String msgText, String imgPath) {
Intent intent = new Intent(Intent.ACTION_SEND);
if (imgPath == null || imgPath.equals("")) {
intent.setType("text/plain"); // 纯文本
} else {
File f = new File(imgPath);
if (f != null && f.exists() && f.isFile()) {
intent.setType("image/jpg");
Uri u = Uri.fromFile(f);
intent.putExtra(Intent.EXTRA_STREAM, u);
}
}
intent.putExtra(Intent.EXTRA_SUBJECT, msgTitle);
intent.putExtra(Intent.EXTRA_TEXT, msgText);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(Intent.createChooser(intent, "分享到"));
}
/**
* 获得屏幕宽度
* @param context
* @return
*/
public static int getScreenWidth(Context context)
{
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
return outMetrics.widthPixels;
}
/**
* 获得屏幕高度
* @param context
* @return
*/
public static int getScreenHeight(Context context) {
WindowManager wm = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
return outMetrics.heightPixels;
}
public static String date2string(Date date) {
String strDate = "";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
strDate = sdf.format(date);
return strDate;
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
app/src/main/java/com/ns/yc/yccustomtext/MainActivity.java | Java | package com.ns.yc.yccustomtext;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.ns.yc.yccustomtextlib.utils.HyperLogUtils;
import com.pedaily.yc.ycdialoglib.toast.ToastUtils;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private TextView tv_1;
private TextView tv_2;
private TextView tv_3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
HyperLogUtils.setIsLog(true);
ToastUtils.init(getApplication());
}
private void init() {
tv_1 = (TextView) findViewById(R.id.tv_1);
tv_1.setOnClickListener(this);
tv_2 = (TextView) findViewById(R.id.tv_2);
tv_2.setOnClickListener(this);
tv_3 = (TextView) findViewById(R.id.tv_3);
tv_3.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.tv_1:
startActivity(new Intent(this, NewArticleActivity.class));
break;
case R.id.tv_2:
startActivity(new Intent(MainActivity.this,WebRichActivity.class));
break;
case R.id.tv_3:
startActivity(new Intent(MainActivity.this,AlignActivity.class));
break;
default:
break;
}
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
app/src/main/java/com/ns/yc/yccustomtext/ModelStorage.java | Java | package com.ns.yc.yccustomtext;
import com.ns.yc.yccustomtextlib.edit.model.HyperEditData;
import java.util.ArrayList;
import java.util.List;
/**
* <pre>
* @author yangchong
* blog : https://github.com/yangchong211
* time : 2019/9/18
* desc : 数据缓冲区,替代intent传递大数据方案
* revise:
* </pre>
*/
public class ModelStorage {
private List<HyperEditData> hyperEditData = new ArrayList<>();
public static ModelStorage getInstance(){
return SingletonHolder.instance;
}
private static class SingletonHolder{
private static final ModelStorage instance = new ModelStorage();
}
public List<HyperEditData> getHyperEditData() {
return hyperEditData;
}
public void setHyperEditData(List<HyperEditData> hyperEditData) {
this.hyperEditData.clear();
this.hyperEditData.addAll(hyperEditData);
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
app/src/main/java/com/ns/yc/yccustomtext/MyGlideEngine.java | Java | package com.ns.yc.yccustomtext;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.zhihu.matisse.engine.ImageEngine;
/**
* 自定义Glide加载引擎,用于知乎图片选择器
*/
public class MyGlideEngine implements ImageEngine {
@Override
public void loadThumbnail(Context context, int resize, Drawable placeholder, ImageView imageView, Uri uri) {
Glide.with(context)
.asBitmap() // some .jpeg files are actually gif
.load(uri)
.placeholder(placeholder)
.override(resize, resize)
.centerCrop()
.into(imageView);
}
@Override
public void loadGifThumbnail(Context context, int resize, Drawable placeholder, ImageView imageView, Uri uri) {
Glide.with(context)
.asBitmap()
.load(uri)
.placeholder(placeholder)
.override(resize, resize)
.centerCrop()
.into(imageView);
}
@Override
public void loadImage(Context context, int resizeX, int resizeY, ImageView imageView, Uri uri) {
Glide.with(context)
.load(uri)
.override(resizeX, resizeY)
.priority(Priority.HIGH)
.into(imageView);
}
@Override
public void loadGifImage(Context context, int resizeX, int resizeY, ImageView imageView, Uri uri) {
Glide.with(context)
.asGif()
.load(uri)
.override(resizeX, resizeY)
.priority(Priority.HIGH)
.into(imageView);
}
@Override
public boolean supportAnimatedGif() {
return true;
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
app/src/main/java/com/ns/yc/yccustomtext/NewArticleActivity.java | Java | package com.ns.yc.yccustomtext;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.gson.Gson;
import com.ns.yc.yccustomtextlib.edit.inter.OnHyperChangeListener;
import com.ns.yc.yccustomtextlib.edit.manager.HyperManager;
import com.ns.yc.yccustomtextlib.edit.inter.ImageLoader;
import com.ns.yc.yccustomtextlib.edit.inter.OnHyperEditListener;
import com.ns.yc.yccustomtextlib.edit.inter.OnHyperTextListener;
import com.ns.yc.yccustomtextlib.edit.model.HyperEditData;
import com.ns.yc.yccustomtextlib.edit.view.HyperImageView;
import com.ns.yc.yccustomtextlib.utils.HyperHtmlUtils;
import com.ns.yc.yccustomtextlib.utils.HyperLibUtils;
import com.ns.yc.yccustomtextlib.edit.view.HyperTextEditor;
import com.ns.yc.yccustomtextlib.edit.view.HyperTextView;
import com.ns.yc.yccustomtextlib.utils.HyperLogUtils;
import com.pedaily.yc.ycdialoglib.fragment.CustomDialogFragment;
import com.pedaily.yc.ycdialoglib.toast.ToastUtils;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;
import java.util.List;
import cn.ycbjie.ycstatusbarlib.bar.StateAppBar;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
public class NewArticleActivity extends AppCompatActivity {
private static final int REQUEST_CODE_CHOOSE = 520;
private Toolbar toolbar;
private HyperTextEditor hte_content;
private HyperTextView htv_content;
private int screenWidth;
private int screenHeight;
private Disposable subsInsert;
private Disposable mDisposable;
@Override
public void onBackPressed() {
super.onBackPressed();
//判断键盘是否弹出
boolean softInputVisible = HyperLibUtils.isSoftInputVisible(this);
if (softInputVisible){
HyperLibUtils.hideSoftInput(this);
}
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new);
StateAppBar.setStatusBarColor(this, ContextCompat.getColor(this, R.color.colorPrimary));
toolbar = findViewById(R.id.toolbar);
hte_content = findViewById(R.id.hte_content);
htv_content = findViewById(R.id.htv_content);
initToolBar();
screenWidth = CommonUtil.getScreenWidth(this);
screenHeight = CommonUtil.getScreenHeight(this);
initListener();
initHyper();
//解决点击EditText弹出收起键盘时出现的黑屏闪现现象
View rootView = hte_content.getRootView();
rootView.setBackgroundColor(Color.WHITE);
hte_content.postDelayed(new Runnable() {
@Override
public void run() {
EditText lastFocusEdit = hte_content.getLastFocusEdit();
lastFocusEdit.requestFocus();
//打开软键盘显示
//HyperLibUtils.openSoftInput(NewArticleActivity.this);
}
},300);
}
private void initListener() {
final TextView tv_length = findViewById(R.id.tv_length);
TextView tv_0_1 = findViewById(R.id.tv_0_1);
TextView tv_0_2 = findViewById(R.id.tv_0_2);
TextView tv_1 = findViewById(R.id.tv_1);
TextView tv_2 = findViewById(R.id.tv_2);
TextView tv_3 = findViewById(R.id.tv_3);
TextView tv_4 = findViewById(R.id.tv_4);
TextView tv_4_2 = findViewById(R.id.tv_4_2);
TextView tv_5 = findViewById(R.id.tv_5);
TextView tv_6 = findViewById(R.id.tv_6);
tv_1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//加粗
hte_content.bold();
}
});
tv_2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//下划线
hte_content.underline();
}
});
tv_3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//斜体
hte_content.italic();
}
});
tv_4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//删除线样式
hte_content.strikeThrough();
}
});
tv_4_2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//加粗斜体
hte_content.boldItalic();
}
});
tv_0_1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//编辑
hte_content.setVisibility(View.VISIBLE);
htv_content.setVisibility(View.GONE);
}
});
tv_0_2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//保存
showDataSync(getEditData());
}
});
tv_5.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
List<HyperEditData> editList = hte_content.buildEditData();
//生成json
Gson gson = new Gson();
String content = gson.toJson(editList);
//转化成json字符串
String string = HyperHtmlUtils.stringToJson(content);
Intent intent = new Intent(NewArticleActivity.this, TextActivity.class);
intent.putExtra("content", string);
startActivity(intent);
}
});
tv_6.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//生成html
}
});
hte_content.setOnHyperListener(new OnHyperEditListener() {
@Override
public void onImageClick(View view, String imagePath) {
//图片点击事件
ToastUtils.showRoundRectToast("图片点击"+imagePath);
}
@Override
public void onRtImageDelete(String imagePath) {
//图片删除成功事件
ToastUtils.showRoundRectToast("图片删除成功");
}
@Override
public void onImageCloseClick(final View view) {
//图片删除图片点击事件
CustomDialogFragment
.create((NewArticleActivity.this).getSupportFragmentManager())
.setTitle("删除图片")
.setContent("确定要删除该图片吗?")
.setCancelContent("取消")
.setOkContent("确定")
.setDimAmount(0.5f)
.setOkColor(NewArticleActivity.this.getResources().getColor(R.color.color_000000))
.setCancelOutside(true)
.setCancelListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CustomDialogFragment.dismissDialogFragment();
}
})
.setOkListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CustomDialogFragment.dismissDialogFragment();
hte_content.onImageCloseClick(view);
}
})
.show();
}
});
hte_content.setOnHyperChangeListener(new OnHyperChangeListener() {
@Override
public void onImageClick(int contentLength, int imageLength) {
//富文本的文字数量,图片数量统计
tv_length.setText("文字共"+contentLength+"个字,图片共"+imageLength+"张");
}
});
htv_content.setOnHyperTextListener(new OnHyperTextListener() {
@Override
public void onImageClick(View view, String imagePath) {
//图片点击事件
}
});
}
private void initToolBar() {
setSupportActionBar(toolbar);
toolbar.setTitle("新建富文本");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_new, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.insert_image:
//插入图片
HyperLibUtils.hideSoftInput(this);
PermissionUtils.checkWritePermissionsRequest(this, new PermissionCallBack() {
@Override
public void onPermissionGranted(Context context) {
callGallery();
}
@Override
public void onPermissionDenied(Context context, int type) {
}
});
break;
case R.id.save:
//保存
List<HyperEditData> hyperEditData = hte_content.buildEditData();
ModelStorage.getInstance().setHyperEditData(hyperEditData);
startActivity(new Intent(this,PreviewArticleActivity.class));
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onStop() {
super.onStop();
try {
if (subsInsert != null && subsInsert.isDisposed()){
subsInsert.dispose();
}
if (mDisposable != null && !mDisposable.isDisposed()){
mDisposable.dispose();
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (data != null) {
if (requestCode == REQUEST_CODE_CHOOSE){
//异步方式插入图片
insertImagesSync(data);
}
}
}
}
/**
* 异步方式插入图片
*/
private void insertImagesSync(final Intent data){
Observable.create(new ObservableOnSubscribe<String>() {
@Override
public void subscribe(ObservableEmitter<String> emitter) {
try{
hte_content.measure(0, 0);
List<Uri> mSelected = Matisse.obtainResult(data);
// 可以同时插入多张图片
for (Uri imageUri : mSelected) {
String imagePath = HyperLibUtils.getFilePathFromUri(NewArticleActivity.this, imageUri);
Bitmap bitmap = HyperLibUtils.getSmallBitmap(imagePath, screenWidth, screenHeight);
//压缩图片
imagePath = SDCardUtil.saveToSdCard(bitmap);
//Log.e(TAG, "###imagePath="+imagePath);
emitter.onNext(imagePath);
}
// 测试插入网络图片 http://pics.sc.chinaz.com/files/pic/pic9/201904/zzpic17414.jpg
//emitter.onNext("http://pics.sc.chinaz.com/files/pic/pic9/201903/zzpic16838.jpg");
//emitter.onNext("http://b.zol-img.com.cn/sjbizhi/images/10/640x1136/1572123845476.jpg");
//emitter.onNext("https://img.ivsky.com/img/tupian/pre/201903/24/richu_riluo-013.jpg");
emitter.onComplete();
}catch (Exception e){
e.printStackTrace();
emitter.onError(e);
}
}
})
//.onBackpressureBuffer()
.subscribeOn(Schedulers.io())//生产事件在io
.observeOn(AndroidSchedulers.mainThread())//消费事件在UI线程
.subscribe(new Observer<String>() {
@Override
public void onComplete() {
ToastUtils.showRoundRectToast("图片插入成功");
}
@Override
public void onError(Throwable e) {
ToastUtils.showRoundRectToast("图片插入失败:"+e.getMessage());
}
@Override
public void onSubscribe(Disposable d) {
subsInsert = d;
}
@Override
public void onNext(String imagePath) {
hte_content.insertImage(imagePath);
}
});
}
/**
* 异步方式显示数据
*/
private void showDataSync(final String html){
if (html==null || html.length()==0){
return;
}
htv_content.clearAllLayout();
Observable.create(new ObservableOnSubscribe<String>() {
@Override
public void subscribe(ObservableEmitter<String> emitter) {
showEditData(emitter, html);
}
})
//.onBackpressureBuffer()
.subscribeOn(Schedulers.io())//生产事件在io
.observeOn(AndroidSchedulers.mainThread())//消费事件在UI线程
.subscribe(new Observer<String>() {
@Override
public void onComplete() {
}
@Override
public void onError(Throwable e) {
ToastUtils.showRoundRectToast("解析错误:图片不存在或已损坏");
}
@Override
public void onSubscribe(Disposable d) {
mDisposable = d;
}
@Override
public void onNext(String text) {
try {
htv_content.setVisibility(View.VISIBLE);
hte_content.setVisibility(View.GONE);
if (htv_content !=null) {
if (text.contains("<img") && text.contains("src=")) {
//imagePath可能是本地路径,也可能是网络地址
String imagePath = HyperLibUtils.getImgSrc(text);
htv_content.addImageViewAtIndex(htv_content.getLastIndex(), imagePath);
} else {
htv_content.addTextViewAtIndex(htv_content.getLastIndex(), text);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* 显示数据
*/
private void showEditData(ObservableEmitter<String> emitter, String html) {
try {
List<String> textList = HyperLibUtils.cutStringByImgTag(html);
for (int i = 0; i < textList.size(); i++) {
String text = textList.get(i);
emitter.onNext(text);
}
emitter.onComplete();
} catch (Exception e){
e.printStackTrace();
emitter.onError(e);
}
}
/**
* 负责处理编辑数据提交等事宜,请自行实现
*/
private String getEditData() {
StringBuilder content = new StringBuilder();
try {
List<HyperEditData> editList = hte_content.buildEditData();
for (HyperEditData itemData : editList) {
if (itemData.getInputStr() != null) {
content.append(itemData.getInputStr());
} else if (itemData.getImagePath() != null) {
content.append("<img src=\"").append(itemData.getImagePath()).append("\"/>");
}
}
} catch (Exception e) {
e.printStackTrace();
}
return content.toString();
}
/**
* 调用图库选择
*/
private void callGallery(){
Matisse.from(this)
.choose(MimeType.of(MimeType.JPEG, MimeType.PNG, MimeType.GIF))//照片视频全部显示MimeType.allOf()
.countable(true)//true:选中后显示数字;false:选中后显示对号
.maxSelectable(3)//最大选择数量为9
//.addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
.gridExpectedSize(this.getResources().getDimensionPixelSize(R.dimen.photo))//图片显示表格的大小
.restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)//图像选择和预览活动所需的方向
.thumbnailScale(0.85f)//缩放比例
.theme(R.style.Matisse_Zhihu)//主题 暗色主题 R.style.Matisse_Dracula
.imageEngine(new MyGlideEngine())//图片加载方式,Glide4需要自定义实现
.capture(true) //是否提供拍照功能,兼容7.0系统需要下面的配置
//参数1 true表示拍照存储在共有目录,false表示存储在私有目录;参数2与 AndroidManifest中authorities值相同,用于适配7.0系统 必须设置
.captureStrategy(new CaptureStrategy(true,"com.sendtion.matisse.fileprovider"))//存储到哪里
.forResult(REQUEST_CODE_CHOOSE);//请求码
}
private void initHyper(){
HyperManager.getInstance().setImageLoader(new ImageLoader() {
@Override
public void loadImage(final String imagePath, final HyperImageView imageView, final int imageHeight) {
Log.e("---", "imageHeight: "+imageHeight);
//如果是网络图片
if (imagePath.startsWith("http://") || imagePath.startsWith("https://")){
Glide.with(getApplicationContext()).asBitmap()
.load(imagePath)
.dontAnimate()
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
if (imageHeight > 0) {//固定高度
if (imageView.getLayoutParams() instanceof RelativeLayout.LayoutParams){
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT, imageHeight);//固定图片高度,记得设置裁剪剧中
lp.bottomMargin = 10;//图片的底边距
imageView.setLayoutParams(lp);
} else if (imageView.getLayoutParams() instanceof FrameLayout.LayoutParams){
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT, imageHeight);//固定图片高度,记得设置裁剪剧中
lp.bottomMargin = 10;//图片的底边距
imageView.setLayoutParams(lp);
}
Glide.with(getApplicationContext()).asBitmap().load(imagePath).centerCrop()
.placeholder(R.drawable.img_load_fail).error(R.drawable.img_load_fail).into(imageView);
} else {//自适应高度
Glide.with(getApplicationContext()).asBitmap().load(imagePath)
.placeholder(R.drawable.img_load_fail).error(R.drawable.img_load_fail).into(new TransformationScale(imageView));
}
}
});
} else { //如果是本地图片
// if (imageHeight > 0) {//固定高度
// if (imageView.getLayoutParams() instanceof RelativeLayout.LayoutParams){
// RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
// FrameLayout.LayoutParams.MATCH_PARENT, imageHeight);//固定图片高度,记得设置裁剪剧中
// lp.bottomMargin = 10;//图片的底边距
// imageView.setLayoutParams(lp);
// } else if (imageView.getLayoutParams() instanceof FrameLayout.LayoutParams){
// FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
// FrameLayout.LayoutParams.MATCH_PARENT, imageHeight);//固定图片高度,记得设置裁剪剧中
// lp.bottomMargin = 10;//图片的底边距
// imageView.setLayoutParams(lp);
// }
//
// Glide.with(getApplicationContext()).asBitmap().load(imagePath).centerCrop()
// .placeholder(R.drawable.img_load_fail).error(R.drawable.img_load_fail).into(imageView);
// } else {//自适应高度
// Glide.with(getApplicationContext()).asBitmap().load(imagePath)
// .placeholder(R.drawable.img_load_fail).error(R.drawable.img_load_fail).into(new TransformationScale(imageView));
// }
if (imageHeight>0){
Glide.with(getApplicationContext())
.asBitmap()
.load(imagePath)
.centerCrop()
.placeholder(R.drawable.img_load_fail)
.error(R.drawable.img_load_fail)
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
int width = resource.getWidth();
int height = resource.getHeight();
HyperLogUtils.d("本地图片--3--"+height+"----"+width);
imageView.setImageBitmap(resource);
ViewParent parent = imageView.getParent();
int imageHeight = 0;
//单个图片最高200,最小高度100,图片按高度宽度比例,通过改变夫布局来控制动态高度
if (height> HyperLibUtils.dip2px(NewArticleActivity.this,200)){
if (parent instanceof RelativeLayout){
ViewGroup.LayoutParams layoutParams = ((RelativeLayout) parent).getLayoutParams();
layoutParams.height = HyperLibUtils.dip2px(NewArticleActivity.this,200);
((RelativeLayout) parent).setLayoutParams(layoutParams);
} else if (parent instanceof FrameLayout){
ViewGroup.LayoutParams layoutParams = ((FrameLayout) parent).getLayoutParams();
layoutParams.height = HyperLibUtils.dip2px(NewArticleActivity.this,200);
((FrameLayout) parent).setLayoutParams(layoutParams);
HyperLogUtils.d("本地图片--4--");
}
imageHeight = HyperLibUtils.dip2px(NewArticleActivity.this,200);
} else if (height>HyperLibUtils.dip2px(NewArticleActivity.this,100)
&& height<HyperLibUtils.dip2px(NewArticleActivity.this,200)){
//自是因高度
HyperLogUtils.d("本地图片--5--");
imageHeight = height;
} else {
if (parent instanceof RelativeLayout){
ViewGroup.LayoutParams layoutParams = ((RelativeLayout) parent).getLayoutParams();
layoutParams.height = HyperLibUtils.dip2px(NewArticleActivity.this,100);
((RelativeLayout) parent).setLayoutParams(layoutParams);
} else if (parent instanceof FrameLayout){
ViewGroup.LayoutParams layoutParams = ((FrameLayout) parent).getLayoutParams();
layoutParams.height = HyperLibUtils.dip2px(NewArticleActivity.this,100);
((FrameLayout) parent).setLayoutParams(layoutParams);
HyperLogUtils.d("本地图片--6--");
}
imageHeight = HyperLibUtils.dip2px(NewArticleActivity.this,100);
}
//设置图片的属性,图片的底边距,以及图片的动态高度
if (imageView.getLayoutParams() instanceof RelativeLayout.LayoutParams){
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT, imageHeight);//固定图片高度,记得设置裁剪剧中
lp.bottomMargin = 10;//图片的底边距
imageView.setLayoutParams(lp);
} else if (imageView.getLayoutParams() instanceof FrameLayout.LayoutParams){
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT, imageHeight);//固定图片高度,记得设置裁剪剧中
lp.bottomMargin = 10;//图片的底边距
imageView.setLayoutParams(lp);
}
}
});
} else {
Glide.with(getApplicationContext())
.asBitmap()
.load(imagePath)
.placeholder(R.drawable.img_load_fail)
.error(R.drawable.img_load_fail)
.into(new TransformationScale(imageView));
}
}
}
});
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
app/src/main/java/com/ns/yc/yccustomtext/PermissionCallBack.java | Java | package com.ns.yc.yccustomtext;
import android.content.Context;
/**
* <pre>
* @author yangchong
* blog : https://github.com/yangchong211
* time : 2019/9/10
* desc : 权限申请回调callback
* revise:
* </pre>
*/
public interface PermissionCallBack {
/**
* 拒绝权限
*/
int REFUSE = 1;
/**
* 权限申请失败
*/
int DEFEATED = 2;
/**
* 申请权限成功
* @param context 上下文
*/
void onPermissionGranted(Context context);
/**
* 申请权限失败
* @param context 上下文
* @param type 类型,1是拒绝权限,2是申请失败
*/
void onPermissionDenied(Context context, int type);
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
app/src/main/java/com/ns/yc/yccustomtext/PermissionUtils.java | Java | package com.ns.yc.yccustomtext;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.app.FragmentActivity;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;
import java.util.concurrent.TimeUnit;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
/**
* <pre>
* @author yangchong
* blog : https://github.com/yangchong211
* time : 2019/9/10
* desc : 权限申请工具类
* revise:
* </pre>
*/
public class PermissionUtils {
/**
* 注意要点:
* 第一个:this 参数可以是 FragmentActivity 或 Fragment。
* 如果你在 fragment 中使用 RxPermissions,你应该传递 fragment 实例,而不是fragment.getActivity()
* 第二个:请求权限,必须在初始化阶段比如 onCreate 中调用
* 应用程序可能在权限请求期间重新启动,因此请求必须在初始化阶段完成。
* 第三个:统一规范权限,避免混乱
* 第四个:该库可以和rx结合使用
*
* 参考案例:https://github.com/tbruyelle/RxPermissions
*/
/**
* 定位权限
*/
private static String[] LOCATION = new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION};
/**
* 电话
*/
private static String[] PHONE = new String[]{Manifest.permission.CALL_PHONE,};
/**
* 读写存储权限
*/
private static String[] WRITE = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE};
/**
* 短信权限
*/
private static String[] SMS = new String[]{Manifest.permission.SEND_SMS,};
/**
* 相机权限,相机权限包括读写文件权限
*/
private static String[] CAMERA = new String[]{Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE};
/**
* 定位权限
* @param activity activity
* @param callBack 回调callBack
*/
@SuppressLint("CheckResult")
public static void checkLocationPermission(final FragmentActivity activity,
final PermissionCallBack callBack) {
RxPermissions rxPermissions = new RxPermissions(activity);
//request 不支持返回权限名,返回的权限结果:全部同意时值true,否则值为false
rxPermissions
.request(LOCATION)
.subscribe(new Consumer<Boolean>() {
@Override
public void accept(Boolean aBoolean) throws Exception {
if (aBoolean) {
//已经获得权限
callBack.onPermissionGranted(activity);
} else {
//用户拒绝开启权限,且选了不再提示时,才会走这里,否则会一直请求开启
callBack.onPermissionDenied(activity, PermissionCallBack.REFUSE);
}
}
});
}
/**
* 读写权限
* @param activity activity
* @param callBack 回调callBack
*/
@SuppressLint("CheckResult")
public static void checkWritePermissionsTime(final FragmentActivity activity,
final PermissionCallBack callBack) {
RxPermissions rxPermissions = new RxPermissions(activity);
//ensure
//必须配合rxJava,回调结果与request一样,不过这个可以延迟操作
Observable.timer(10, TimeUnit.MILLISECONDS)
.compose(rxPermissions.ensure(WRITE))
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<Boolean>() {
@Override
public void accept(Boolean aBoolean) throws Exception {
if (aBoolean) {
//已经获得权限
callBack.onPermissionGranted(activity);
} else {
//用户拒绝开启权限,且选了不再提示时,才会走这里,否则会一直请求开启
callBack.onPermissionDenied(activity, PermissionCallBack.REFUSE);
}
}
});
}
/**
* 读写权限
* @param activity activity
* @param callBack 回调callBack
*/
@SuppressLint("CheckResult")
public static void checkWritePermissionsRequest(final FragmentActivity activity,
final PermissionCallBack callBack) {
RxPermissions rxPermissions = new RxPermissions(activity);
//request 不支持返回权限名,返回的权限结果:全部同意时值true,否则值为false
rxPermissions
.request(WRITE)
.subscribe(new Consumer<Boolean>() {
@Override
public void accept(Boolean aBoolean) throws Exception {
if (aBoolean) {
//已经获得权限
callBack.onPermissionGranted(activity);
} else {
//用户拒绝开启权限,且选了不再提示时,才会走这里,否则会一直请求开启
callBack.onPermissionDenied(activity, PermissionCallBack.REFUSE);
}
}
});
}
/**
* 相机权限
* @param activity activity
* @param callBack 回调callBack
*/
@SuppressLint("CheckResult")
public static void checkCameraPermissions(final FragmentActivity activity,
final PermissionCallBack callBack) {
RxPermissions rxPermissions = new RxPermissions(activity);
//requestEachCombined
//返回的权限名称:将多个权限名合并成一个
//返回的权限结果:全部同意时值true,否则值为false
rxPermissions
.requestEachCombined(CAMERA)
.subscribe(new Consumer<Permission>() {
@Override
public void accept(Permission permission) throws Exception {
boolean shouldShowRequestPermissionRationale =
permission.shouldShowRequestPermissionRationale;
if (permission.granted) {
// 用户已经同意该权限
callBack.onPermissionGranted(activity);
} else if (shouldShowRequestPermissionRationale) {
// 用户拒绝了该权限,没有选中『不再询问』(Never ask again)
// 那么下次再次启动时。还会提示请求权限的对话框
callBack.onPermissionDenied(activity, PermissionCallBack.DEFEATED);
} else {
// 用户拒绝了该权限,而且选中『不再询问』那么下次启动时,就不会提示出来了,
callBack.onPermissionDenied(activity, PermissionCallBack.REFUSE);
}
}
});
}
/**
* 检测短信息权限
* @param activity activity
* @param callBack 回调callBack
*/
@SuppressLint("CheckResult")
public static void checkSmsPermissions(final FragmentActivity activity,
final PermissionCallBack callBack) {
RxPermissions rxPermissions = new RxPermissions(activity);
//requestEach 把每一个权限的名称和申请结果都列出来
rxPermissions
.requestEach(SMS)
.subscribe(new Consumer<Permission>() {
@Override
public void accept(Permission permission) throws Exception {
boolean shouldShowRequestPermissionRationale =
permission.shouldShowRequestPermissionRationale;
if (permission.granted) {
// 用户已经同意该权限
callBack.onPermissionGranted(activity);
} else if (shouldShowRequestPermissionRationale) {
// 用户拒绝了该权限,没有选中『不再询问』(Never ask again)
// 那么下次再次启动时。还会提示请求权限的对话框
callBack.onPermissionDenied(activity, PermissionCallBack.DEFEATED);
} else {
// 用户拒绝了该权限,而且选中『不再询问』那么下次启动时,就不会提示出来了,
callBack.onPermissionDenied(activity, PermissionCallBack.REFUSE);
}
}
});
}
/**
* 检测电话权限
* @param activity activity
* @param callBack 回调callBack
*/
@SuppressLint("CheckResult")
public static void checkPhonePermissions(final FragmentActivity activity,
final PermissionCallBack callBack) {
RxPermissions rxPermissions = new RxPermissions(activity);
//request 不支持返回权限名,返回的权限结果:全部同意时值true,否则值为false
rxPermissions
.request(PHONE)
.subscribe(new Consumer<Boolean>() {
@Override
public void accept(Boolean aBoolean) throws Exception {
if (aBoolean) {
//已经获得权限
callBack.onPermissionGranted(activity);
} else {
//用户拒绝开启权限,且选了不再提示时,才会走这里,否则会一直请求开启
callBack.onPermissionDenied(activity, PermissionCallBack.REFUSE);
}
}
});
}
/**
* 拨打电话
* @param activity 上下文
* @param telephoneNumber 电话
*/
public static void callPhone(final FragmentActivity activity, final String telephoneNumber) {
if (activity == null || telephoneNumber == null || telephoneNumber.length() == 0) {
return;
}
checkPhonePermissions(activity, new PermissionCallBack() {
@Override
public void onPermissionGranted(Context context) {
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + telephoneNumber));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(intent);
}
@Override
public void onPermissionDenied(Context context, int type) {
}
});
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
app/src/main/java/com/ns/yc/yccustomtext/PreviewArticleActivity.java | Java | package com.ns.yc.yccustomtext;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.ns.yc.yccustomtextlib.edit.inter.ImageLoader;
import com.ns.yc.yccustomtextlib.edit.inter.OnHyperTextListener;
import com.ns.yc.yccustomtextlib.edit.manager.HyperManager;
import com.ns.yc.yccustomtextlib.edit.model.HyperEditData;
import com.ns.yc.yccustomtextlib.edit.view.HyperImageView;
import com.ns.yc.yccustomtextlib.edit.view.HyperTextView;
import java.util.List;
import cn.ycbjie.ycstatusbarlib.bar.StateAppBar;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2019/01/09
* desc : 预览页面
* revise:
* </pre>
*/
public class PreviewArticleActivity extends AppCompatActivity {
private HyperTextView htvContent;
private Disposable mDisposable;
@Override
protected void onStop() {
super.onStop();
try {
if (mDisposable != null && !mDisposable.isDisposed()){
mDisposable.dispose();
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_preview_article);
StateAppBar.setStatusBarLightMode(this, Color.WHITE);
htvContent = findViewById(R.id.htv_content);
TextView tv_title = findViewById(R.id.tv_title);
ImageView iv_image = findViewById(R.id.iv_image);
TextView tv_name = findViewById(R.id.tv_name);
TextView tv_time = findViewById(R.id.tv_time);
initHyper();
List<HyperEditData> hyperEditData = ModelStorage.getInstance().getHyperEditData();
showDataSync(hyperEditData);
Glide.with(getApplicationContext())
.asBitmap()
.load(R.drawable.shape_load_bg)
.placeholder(R.drawable.img_load_fail)
.error(R.drawable.img_load_fail)
.into(iv_image);
htvContent.setOnHyperTextListener(new OnHyperTextListener() {
@Override
public void onImageClick(View view, String imagePath) {
}
});
}
/**
* 异步方式显示数据
*/
private void showDataSync(final List<HyperEditData> content){
if (content==null || content.size()==0){
return;
}
htvContent.clearAllLayout();
Observable.create(new ObservableOnSubscribe<HyperEditData>() {
@Override
public void subscribe(ObservableEmitter<HyperEditData> emitter) {
try {
for (int i=0; i<content.size(); i++){
//这个有点像是thread线程中的join方法,主要是保证顺序执行。
//比如,开始3个线程,如果执行结果按照顺序,则需要用到join方法,具体原理可以看看emitter.onNext源码
emitter.onNext(content.get(i));
}
emitter.onComplete();
} catch (Exception e){
e.printStackTrace();
emitter.onError(e);
}
}
})
//.onBackpressureBuffer()
.subscribeOn(Schedulers.io())//生产事件在io
.observeOn(AndroidSchedulers.mainThread())//消费事件在UI线程
.subscribe(new Observer<HyperEditData>() {
@Override
public void onComplete() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onSubscribe(Disposable d) {
mDisposable = d;
}
@Override
public void onNext(HyperEditData bean) {
try {
int type = bean.getType();
switch (type){
//文字类型
case 1:
htvContent.addTextViewAtIndex(htvContent.getLastIndex(), bean.getInputStr());
break;
//图片类型
case 2:
htvContent.addImageViewAtIndex(htvContent.getLastIndex(), bean.getImagePath());
break;
default:
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private void initHyper(){
HyperManager.getInstance().setImageLoader(new ImageLoader() {
@Override
public void loadImage(final String imagePath, final HyperImageView imageView, final int imageHeight) {
Glide.with(getApplicationContext())
.asBitmap()
.load(imagePath)
.placeholder(R.drawable.img_load_fail)
.error(R.drawable.img_load_fail)
.into(new TransformationScale(imageView));
}
});
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
app/src/main/java/com/ns/yc/yccustomtext/SDCardUtil.java | Java | package com.ns.yc.yccustomtext;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class SDCardUtil {
public static String SDCardRoot = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;
public static String APP_NAME = "HyperManager";
/**
* 检查是否存在SDCard
*/
public static boolean hasSdcard(){
String state = Environment.getExternalStorageState();
if(state.equals(Environment.MEDIA_MOUNTED)){
return true;
}else{
return false;
}
}
/**
* 获得文章图片保存路径
*/
public static String getPictureDir(){
String imageCacheUrl = SDCardRoot + APP_NAME + File.separator;
File file = new File(imageCacheUrl);
if(!file.exists())
file.mkdirs(); //如果不存在则创建
return imageCacheUrl;
}
/**
* 图片保存到SD卡
* @param bitmap
* @return
*/
public static String saveToSdCard(Bitmap bitmap) {
String imageUrl = getPictureDir() + System.currentTimeMillis() + "-";
File file = new File(imageUrl);
try {
FileOutputStream out = new FileOutputStream(file);
if (bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out)) {
out.flush();
out.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return file.getAbsolutePath();
}
/**
* 根据Uri获取图片文件的绝对路径
*/
public static String getFilePathByUri(Context context, final Uri uri) {
if (null == uri) {
return null;
}
final String scheme = uri.getScheme();
String data = null;
if (scheme == null) {
data = uri.getPath();
} else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
data = uri.getPath();
} else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
Cursor cursor = context.getContentResolver().query(uri,
new String[] { MediaStore.Images.ImageColumns.DATA }, null, null, null);
if (null != cursor) {
if (cursor.moveToFirst()) {
int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
if (index > -1) {
data = cursor.getString(index);
}
}
cursor.close();
}
}
return data;
}
/**
* 根据Uri获取真实的文件路径
*
* @param context
* @param uri
* @return
*/
public static String getFilePathFromUri(Context context, Uri uri) {
if (uri == null) return null;
ContentResolver resolver = context.getContentResolver();
FileInputStream input = null;
FileOutputStream output = null;
try {
ParcelFileDescriptor pfd = resolver.openFileDescriptor(uri, "r");
if (pfd == null) {
return null;
}
FileDescriptor fd = pfd.getFileDescriptor();
input = new FileInputStream(fd);
File outputDir = context.getCacheDir();
File outputFile = File.createTempFile("image", "tmp", outputDir);
String tempFilename = outputFile.getAbsolutePath();
output = new FileOutputStream(tempFilename);
int read;
byte[] bytes = new byte[4096];
while ((read = input.read(bytes)) != -1) {
output.write(bytes, 0, read);
}
return new File(tempFilename).getAbsolutePath();
} catch (Exception ignored) {
ignored.getStackTrace();
} finally {
try {
if (input != null){
input.close();
}
if (output != null){
output.close();
}
} catch (Throwable t) {
// Do nothing
}
}
return null;
}
/** 删除文件 **/
public static boolean deleteFile(String filePath) {
File file = new File(filePath);
boolean isOk = false;
if (file.isFile() && file.exists())
isOk = file.delete(); // 删除文件
return isOk;
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
app/src/main/java/com/ns/yc/yccustomtext/TextActivity.java | Java | package com.ns.yc.yccustomtext;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class TextActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_text);
Intent intent = getIntent();
String content = intent.getStringExtra("content");
TextView tvContent = findViewById(R.id.tv_content);
tvContent.setText(content);
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
app/src/main/java/com/ns/yc/yccustomtext/TransformationScale.java | Java | package com.ns.yc.yccustomtext;
import android.graphics.Bitmap;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import com.bumptech.glide.request.target.ImageViewTarget;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2016/3/31
* desc : Glide加载图片时,根据图片宽度等比缩放
* revise:
* </pre>
*/
public class TransformationScale extends ImageViewTarget<Bitmap> {
private ImageView target;
public TransformationScale(ImageView target) {
super(target);
this.target = target;
}
@Override
protected void setResource(Bitmap resource) {
//设置图片
target.setImageBitmap(resource);
if (resource != null) {
//获取原图的宽高
int width = resource.getWidth();
int height = resource.getHeight();
//获取imageView的宽
int imageViewWidth = target.getWidth();
//计算缩放比例
float sy = (float) (imageViewWidth * 0.1) / (float) (width * 0.1);
//计算图片等比例放大后的高
int imageHeight = (int) (height * sy);
//ViewGroup.LayoutParams params = target.getLayoutParams();
//params.height = imageHeight;
//固定图片高度,记得设置裁剪剧中
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT, imageHeight);
params.bottomMargin = 10;
target.setLayoutParams(params);
}
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
app/src/main/java/com/ns/yc/yccustomtext/WebDataActivity.java | Java | package com.ns.yc.yccustomtext;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class WebDataActivity extends AppCompatActivity {
//自己制造的一些假数据。外加筛选图片样式
/**** 3333333333 ***************************************************/
// private String dataStr="<html><body><style>img{ width:100% !important;}</style>"+"<img src=\"https://ss0.bdstatic.com/-0U0bnSm1A5BphGlnYG/tam-ogel/dd9d1d686cdc814db9653b254e00402e_259_194.jpg\" alt=\"\" /> \r<p style=\"text-align:right;\">\r\t品类定位的思考\r</p>\r<h3>\r\t<strong><span style=\"color:#00D5FF;\">品类定</span></strong>\n" +
// "<h3>\r\t<a href='JavaScript:android.returnAndroid(\"要返回给APP的数据\")'>点击我跳回APP</a>"+"</body></html>";
/*** 11111111111 **************************************************************************/
//这个数据的外层不加两层<html><body>标签,不过在下面一个地方加上一个div和图片样式
// private String dataStr = "<img src=\"https://ss0.bdstatic.com/-0U0bnSm1A5BphGlnYG/tam-ogel/dd9d1d686cdc814db9653b254e00402e_259_194.jpg\" alt=\"\" /> \r<p style=\"text-align:right;\">\r\t品类定位的思考\r</p>\r<h3>\r\t<strong><span style=\"color:#00D5FF;\">品类定";
/**** 11111111111 *************************************************************************/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_diarys);
final String dataStr = getIntent().getStringExtra("diarys");
initWebView(dataStr);
}
public void initWebView(String data) {
WebView mWebView = findViewById(R.id.showdiarys);
WebSettings settings = mWebView.getSettings();
//settings.setUseWideViewPort(true);//调整到适合webview的大小,不过尽量不要用,有些手机有问题
settings.setLoadWithOverviewMode(true);//设置WebView是否使用预览模式加载界面。
mWebView.setVerticalScrollBarEnabled(false);//不能垂直滑动
mWebView.setHorizontalScrollBarEnabled(false);//不能水平滑动
settings.setTextSize(WebSettings.TextSize.NORMAL);//通过设置WebSettings,改变HTML中文字的大小
settings.setJavaScriptCanOpenWindowsAutomatically(true);//支持通过JS打开新窗口
//设置WebView属性,能够执行Javascript脚本
mWebView.getSettings().setJavaScriptEnabled(true);//设置js可用
mWebView.setWebViewClient(new WebViewClient());
mWebView.addJavascriptInterface(new AndroidJavaScript(getApplication()), "android");//设置js接口
settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//支持内容重新布局
/****** 22222222 ***********************************************************************/
data = "</Div><head><style>img{ width:100% !important;}</style></head>" + data;//给图片设置一个样式,宽满屏
/****** 2222222222 ***********************************************************************/
mWebView.loadDataWithBaseURL(null, data, "text/html", "utf-8", null);
}
/**
* AndroidJavaScript
* 本地与h5页面交互的js类,这里写成内部类了
* returnAndroid方法上@JavascriptInterface一定不能漏了
*/
private class AndroidJavaScript {
Context mContxt;
public AndroidJavaScript(Context mContxt) {
this.mContxt = mContxt;
}
@JavascriptInterface
public void returnAndroid(String name) {//从网页跳回到APP,这个方法已经在上面的HTML中写上了
if (name.isEmpty() || name.equals("")) {
return;
}
Toast.makeText(getApplication(), name, Toast.LENGTH_SHORT).show();
//这里写你的操作///////////////////////
//MainActivity就是一个空页面,不影响
Intent intent = new Intent(WebDataActivity.this, MainActivity.class);
intent.putExtra("name", name);
startActivity(intent);
}
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
app/src/main/java/com/ns/yc/yccustomtext/WebRichActivity.java | Java | package com.ns.yc.yccustomtext;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.ns.yc.yccustomtextlib.utils.HyperLibUtils;
import com.ns.yc.yccustomtextlib.web.OnTextChangeListener;
import com.ns.yc.yccustomtextlib.web.WebViewRichEditor;
import com.pedaily.yc.ycdialoglib.toast.ToastUtils;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;
import java.util.List;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
public class WebRichActivity extends AppCompatActivity implements View.OnClickListener {
//文本编辑器
private WebViewRichEditor mEditor;
//加粗按钮
private ImageView mBold;
//颜色编辑器
private TextView mTextColor;
//显示显示View
private LinearLayout llColorView;
//预览按钮
private TextView mPreView;
//图片按钮
private TextView mImage;
//按序号排列(ol)
private ImageView mListOL;
//按序号排列(ul)
private ImageView mListUL;
//字体下划线
private ImageView mLean;
//字体倾斜
private ImageView mItalic;
//字体左对齐
private ImageView mAlignLeft;
//字体右对齐
private ImageView mAlignRight;
//字体居中对齐
private ImageView mAlignCenter;
//字体缩进
private ImageView mIndent;
//字体较少缩进
private ImageView mOutdent;
//字体索引
private ImageView mBlockquote;
//字体中划线
private ImageView mStrikethrough;
//字体上标
private ImageView mSuperscript;
//字体下标
private ImageView mSubscript;
//是否加粗
boolean isClickBold = false;
//是否正在执行动画
boolean isAnimating = false;
//是否按ol排序
boolean isListOl = false;
//是否按ul排序
boolean isListUL = false;
//是否下划线字体
boolean isTextLean = false;
//是否下倾斜字体
boolean isItalic = false;
//是否左对齐
boolean isAlignLeft = false;
//是否右对齐
boolean isAlignRight = false;
//是否中对齐
boolean isAlignCenter = false;
//是否缩进
boolean isIndent = false;
//是否较少缩进
boolean isOutdent = false;
//是否索引
boolean isBlockquote = false;
//字体中划线
boolean isStrikethrough = false;
//字体上标
boolean isSuperscript = false;
//字体下标
boolean isSubscript = false;
//折叠视图的宽高
private int mFoldedViewMeasureHeight;
private int screenWidth;
private int screenHeight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_rich);
initView();
initClickListener();
}
/**
* 初始化View
*/
private void initView() {
initEditor();
initMenu();
initColorPicker();
}
/**
* 初始化文本编辑器
*/
private void initEditor() {
mEditor = findViewById(R.id.re_main_editor);
//mEditor.setEditorHeight(400);
//输入框显示字体的大小
mEditor.setEditorFontSize(18);
//输入框显示字体的颜色
mEditor.setEditorFontColor(Color.BLACK);
//输入框背景设置
mEditor.setEditorBackgroundColor(Color.WHITE);
//mEditor.setBackgroundColor(Color.BLUE);
//mEditor.setBackgroundResource(R.drawable.bg);
//mEditor.setBackground("https://raw.githubusercontent.com/wasabeef/art/master/chip.jpg");
//输入框文本padding
mEditor.setPadding(10, 10, 10, 10);
//输入提示文本
mEditor.setPlaceholder("请输入编辑内容");
//是否允许输入
//mEditor.setInputEnabled(false);
//文本输入框监听事件
mEditor.setOnTextChangeListener(new OnTextChangeListener() {
@Override
public void onTextChange(String text) {
Log.d("mEditor", "html文本:" + text);
}
});
screenWidth = CommonUtil.getScreenWidth(this);
screenHeight = CommonUtil.getScreenHeight(this);
}
/**
* 初始化颜色选择器
*/
private void initColorPicker() {
ColorPickerView right = findViewById(R.id.cpv_main_color);
right.setOnColorPickerChangeListener(new ColorPickerView.OnColorPickerChangeListener() {
@Override
public void onColorChanged(ColorPickerView picker, int color) {
mTextColor.setBackgroundColor(color);
mEditor.setTextColor(color);
}
@Override
public void onStartTrackingTouch(ColorPickerView picker) {
}
@Override
public void onStopTrackingTouch(ColorPickerView picker) {
}
});
}
/**
* 初始化菜单按钮
*/
private void initMenu() {
mBold = findViewById(R.id.button_bold);
mTextColor = findViewById(R.id.button_text_color);
llColorView = findViewById(R.id.ll_main_color);
mPreView = findViewById(R.id.tv_main_preview);
mImage = findViewById(R.id.button_image);
mListOL = findViewById(R.id.button_list_ol);
mListUL = findViewById(R.id.button_list_ul);
mLean = findViewById(R.id.button_underline);
mItalic = findViewById(R.id.button_italic);
mAlignLeft = findViewById(R.id.button_align_left);
mAlignRight = findViewById(R.id.button_align_right);
mAlignCenter = findViewById(R.id.button_align_center);
mIndent = findViewById(R.id.button_indent);
mOutdent = findViewById(R.id.button_outdent);
mBlockquote = findViewById(R.id.action_blockquote);
mStrikethrough = findViewById(R.id.action_strikethrough);
mSuperscript = findViewById(R.id.action_superscript);
mSubscript = findViewById(R.id.action_subscript);
getViewMeasureHeight();
}
/**
* 获取控件的高度
*/
private void getViewMeasureHeight() {
//获取像素密度
float mDensity = getResources().getDisplayMetrics().density;
//获取布局的高度
int w = View.MeasureSpec.makeMeasureSpec(0,
View.MeasureSpec.UNSPECIFIED);
int h = View.MeasureSpec.makeMeasureSpec(0,
View.MeasureSpec.UNSPECIFIED);
llColorView.measure(w, h);
int height = llColorView.getMeasuredHeight();
mFoldedViewMeasureHeight = (int) (mDensity * height + 0.5);
}
private void initClickListener() {
mBold.setOnClickListener(this);
mTextColor.setOnClickListener(this);
mPreView.setOnClickListener(this);
mImage.setOnClickListener(this);
mListOL.setOnClickListener(this);
mListUL.setOnClickListener(this);
mLean.setOnClickListener(this);
mItalic.setOnClickListener(this);
mAlignLeft.setOnClickListener(this);
mAlignRight.setOnClickListener(this);
mAlignCenter.setOnClickListener(this);
mIndent.setOnClickListener(this);
mOutdent.setOnClickListener(this);
mBlockquote.setOnClickListener(this);
mStrikethrough.setOnClickListener(this);
mSuperscript.setOnClickListener(this);
mSubscript.setOnClickListener(this);
}
@Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.button_bold) {//字体加粗
if (isClickBold) {
mBold.setImageResource(R.mipmap.bold);
} else { //加粗
mBold.setImageResource(R.mipmap.bold_);
}
isClickBold = !isClickBold;
mEditor.setBold();
} else if (id == R.id.button_text_color) {//设置字体颜色
//如果动画正在执行,直接return,相当于点击无效了,不会出现当快速点击时,
// 动画的执行和ImageButton的图标不一致的情况
if (isAnimating) {
return;
}
//如果动画没在执行,走到这一步就将isAnimating制为true , 防止这次动画还没有执行完毕的
//情况下,又要执行一次动画,当动画执行完毕后会将isAnimating制为false,这样下次动画又能执行
isAnimating = true;
if (llColorView.getVisibility() == View.GONE) {
//打开动画
animateOpen(llColorView);
} else {
//关闭动画
animateClose(llColorView);
}
} else if (id == R.id.button_image) {//插入图片
//这里的功能需要根据需求实现,通过insertImage传入一个URL或者本地图片路径都可以,这里用户可以自己调用本地相
//或者拍照获取图片,传图本地图片路径,也可以将本地图片路径上传到服务器(自己的服务器或者免费的七牛服务器),
//返回在服务端的URL地址,将地址传如即可(我这里传了一张写死的图片URL,如果你插入的图片不现实,请检查你是否添加
// 网络请求权限<uses-permission android:name="android.permission.INTERNET" />)
callGallery();
//mEditor.insertImage("http://www.1honeywan.com/dachshund/image/7.21/7.21_3_thumb.JPG", "dachshund");
} else if (id == R.id.button_list_ol) {
if (isListOl) {
mListOL.setImageResource(R.mipmap.list_ol);
} else {
mListOL.setImageResource(R.mipmap.list_ol_);
}
isListOl = !isListOl;
mEditor.setNumbers();
} else if (id == R.id.button_list_ul) {
if (isListUL) {
mListUL.setImageResource(R.mipmap.list_ul);
} else {
mListUL.setImageResource(R.mipmap.list_ul_);
}
isListUL = !isListUL;
mEditor.setBullets();
} else if (id == R.id.button_underline) {
if (isTextLean) {
mLean.setImageResource(R.mipmap.underline);
} else {
mLean.setImageResource(R.mipmap.underline_);
}
isTextLean = !isTextLean;
mEditor.setUnderline();
} else if (id == R.id.button_italic) {
if (isItalic) {
mItalic.setImageResource(R.mipmap.lean);
} else {
mItalic.setImageResource(R.mipmap.lean_);
}
isItalic = !isItalic;
mEditor.setItalic();
} else if (id == R.id.button_align_left) {
if (isAlignLeft) {
mAlignLeft.setImageResource(R.mipmap.align_left);
} else {
mAlignLeft.setImageResource(R.mipmap.align_left_);
}
isAlignLeft = !isAlignLeft;
mEditor.setAlignLeft();
} else if (id == R.id.button_align_right) {
if (isAlignRight) {
mAlignRight.setImageResource(R.mipmap.align_right);
} else {
mAlignRight.setImageResource(R.mipmap.align_right_);
}
isAlignRight = !isAlignRight;
mEditor.setAlignRight();
} else if (id == R.id.button_align_center) {
if (isAlignCenter) {
mAlignCenter.setImageResource(R.mipmap.align_center);
} else {
mAlignCenter.setImageResource(R.mipmap.align_center_);
}
isAlignCenter = !isAlignCenter;
mEditor.setAlignCenter();
} else if (id == R.id.button_indent) {
if (isIndent) {
mIndent.setImageResource(R.mipmap.indent);
} else {
mIndent.setImageResource(R.mipmap.indent_);
}
isIndent = !isIndent;
mEditor.setIndent();
} else if (id == R.id.button_outdent) {
if (isOutdent) {
mOutdent.setImageResource(R.mipmap.outdent);
} else {
mOutdent.setImageResource(R.mipmap.outdent_);
}
isOutdent = !isOutdent;
mEditor.setOutdent();
} else if (id == R.id.action_blockquote) {
if (isBlockquote) {
mBlockquote.setImageResource(R.mipmap.blockquote);
} else {
mBlockquote.setImageResource(R.mipmap.blockquote_);
}
isBlockquote = !isBlockquote;
mEditor.setBlockquote();
} else if (id == R.id.action_strikethrough) {
if (isStrikethrough) {
mStrikethrough.setImageResource(R.mipmap.strikethrough);
} else {
mStrikethrough.setImageResource(R.mipmap.strikethrough_);
}
isStrikethrough = !isStrikethrough;
mEditor.setStrikeThrough();
} else if (id == R.id.action_superscript) {
if (isSuperscript) {
mSuperscript.setImageResource(R.mipmap.superscript);
} else {
mSuperscript.setImageResource(R.mipmap.superscript_);
}
isSuperscript = !isSuperscript;
mEditor.setSuperscript();
} else if (id == R.id.action_subscript) {
if (isSubscript) {
mSubscript.setImageResource(R.mipmap.subscript);
} else {
mSubscript.setImageResource(R.mipmap.subscript_);
}
isSubscript = !isSubscript;
mEditor.setSubscript();
}
//H1--H6省略,需要的自己添加
else if (id == R.id.tv_main_preview) {//预览
Intent intent = new Intent(WebRichActivity.this, WebDataActivity.class);
intent.putExtra("diarys", mEditor.getHtml());
startActivity(intent);
}
}
/**
* 开启动画
*
* @param view 开启动画的view
*/
private void animateOpen(LinearLayout view) {
view.setVisibility(View.VISIBLE);
ValueAnimator animator = createDropAnimator(view, 0, mFoldedViewMeasureHeight);
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
isAnimating = false;
}
});
animator.start();
}
/**
* 关闭动画
*
* @param view 关闭动画的view
*/
private void animateClose(final LinearLayout view) {
int origHeight = view.getHeight();
ValueAnimator animator = createDropAnimator(view, origHeight, 0);
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
view.setVisibility(View.GONE);
isAnimating = false;
}
});
animator.start();
}
/**
* 创建动画
*
* @param view 开启和关闭动画的view
* @param start view的高度
* @param end view的高度
* @return ValueAnimator对象
*/
private ValueAnimator createDropAnimator(final View view, int start, int end) {
ValueAnimator animator = ValueAnimator.ofInt(start, end);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
int value = (int) animation.getAnimatedValue();
ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
layoutParams.height = value;
view.setLayoutParams(layoutParams);
}
});
return animator;
}
private static final int REQUEST_CODE_CHOOSE = 520;
@Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (data != null) {
if (requestCode == REQUEST_CODE_CHOOSE){
//异步方式插入图片
insertImagesSync(data);
}
}
}
}
/**
* 调用图库选择
*/
private void callGallery(){
Matisse.from(this)
.choose(MimeType.of(MimeType.JPEG, MimeType.PNG, MimeType.GIF))//照片视频全部显示MimeType.allOf()
.countable(true)//true:选中后显示数字;false:选中后显示对号
.maxSelectable(3)//最大选择数量为9
//.addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
.gridExpectedSize(this.getResources().getDimensionPixelSize(R.dimen.photo))//图片显示表格的大小
.restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)//图像选择和预览活动所需的方向
.thumbnailScale(0.85f)//缩放比例
.theme(R.style.Matisse_Zhihu)//主题 暗色主题 R.style.Matisse_Dracula
.imageEngine(new MyGlideEngine())//图片加载方式,Glide4需要自定义实现
.capture(true) //是否提供拍照功能,兼容7.0系统需要下面的配置
//参数1 true表示拍照存储在共有目录,false表示存储在私有目录;参数2与 AndroidManifest中authorities值相同,用于适配7.0系统 必须设置
.captureStrategy(new CaptureStrategy(true,"com.sendtion.matisse.fileprovider"))//存储到哪里
.forResult(REQUEST_CODE_CHOOSE);//请求码
}
/**
* 异步方式插入图片
*/
private void insertImagesSync(final Intent data){
Observable.create(new ObservableOnSubscribe<String>() {
@Override
public void subscribe(ObservableEmitter<String> emitter) {
try{
List<Uri> mSelected = Matisse.obtainResult(data);
// 可以同时插入多张图片
for (Uri imageUri : mSelected) {
String imagePath = HyperLibUtils.getFilePathFromUri(WebRichActivity.this, imageUri);
//Log.e(TAG, "###path=" + imagePath);
Bitmap bitmap = HyperLibUtils.getSmallBitmap(imagePath, screenWidth, screenHeight);
//压缩图片
//bitmap = BitmapFactory.decodeFile(imagePath);
imagePath = SDCardUtil.saveToSdCard(bitmap);
//Log.e(TAG, "###imagePath="+imagePath);
emitter.onNext(imagePath);
}
// 测试插入网络图片 http://pics.sc.chinaz.com/files/pic/pic9/201904/zzpic17414.jpg
//emitter.onNext("http://pics.sc.chinaz.com/files/pic/pic9/201903/zzpic16838.jpg");
//emitter.onNext("http://b.zol-img.com.cn/sjbizhi/images/10/640x1136/1572123845476.jpg");
//emitter.onNext("https://img.ivsky.com/img/tupian/pre/201903/24/richu_riluo-013.jpg");
emitter.onComplete();
}catch (Exception e){
e.printStackTrace();
emitter.onError(e);
}
}
})
//.onBackpressureBuffer()
.subscribeOn(Schedulers.io())//生产事件在io
.observeOn(AndroidSchedulers.mainThread())//消费事件在UI线程
.subscribe(new Observer<String>() {
@Override
public void onComplete() {
ToastUtils.showRoundRectToast("图片插入成功");
}
@Override
public void onError(Throwable e) {
ToastUtils.showRoundRectToast("图片插入失败:"+e.getMessage());
}
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(String imagePath) {
mEditor.insertImage(imagePath, "杨充");
}
});
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
app/src/main/java/com/ns/yc/yccustomtext/WebTextActivity.java | Java | package com.ns.yc.yccustomtext;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class WebTextActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_diarys);
final String dataStr = "http://sctest-ylyc-app.cheoo.com/edit/edit.html";
initWebView(dataStr);
}
public void initWebView(String data) {
WebView mWebView = findViewById(R.id.showdiarys);
WebSettings settings = mWebView.getSettings();
//settings.setUseWideViewPort(true);//调整到适合webview的大小,不过尽量不要用,有些手机有问题
settings.setLoadWithOverviewMode(true);//设置WebView是否使用预览模式加载界面。
mWebView.setVerticalScrollBarEnabled(false);//不能垂直滑动
mWebView.setHorizontalScrollBarEnabled(false);//不能水平滑动
settings.setTextSize(WebSettings.TextSize.NORMAL);//通过设置WebSettings,改变HTML中文字的大小
settings.setJavaScriptCanOpenWindowsAutomatically(true);//支持通过JS打开新窗口
//设置WebView属性,能够执行Javascript脚本
mWebView.getSettings().setJavaScriptEnabled(true);//设置js可用
mWebView.setWebViewClient(new WebViewClient());
mWebView.addJavascriptInterface(new AndroidJavaScript(getApplication()), "android");//设置js接口
settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//支持内容重新布局
mWebView.loadUrl(data);
}
/**
* AndroidJavaScript
* 本地与h5页面交互的js类,这里写成内部类了
* returnAndroid方法上@JavascriptInterface一定不能漏了
*/
private class AndroidJavaScript {
Context mContxt;
public AndroidJavaScript(Context mContxt) {
this.mContxt = mContxt;
}
@JavascriptInterface
public void returnAndroid(String name) {//从网页跳回到APP,这个方法已经在上面的HTML中写上了
if (name.isEmpty() || name.equals("")) {
return;
}
Toast.makeText(getApplication(), name, Toast.LENGTH_SHORT).show();
//这里写你的操作///////////////////////
//MainActivity就是一个空页面,不影响
Intent intent = new Intent(WebTextActivity.this, MainActivity.class);
intent.putExtra("name", name);
startActivity(intent);
}
}
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
app/src/test/java/com/ns/yc/yccustomtext/ExampleUnitTest.java | Java | package com.ns.yc.yccustomtext;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
build.gradle | Gradle | // Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
mavenCentral()
maven { url 'https://jitpack.io' }
}
dependencies {
classpath 'com.android.tools.build:gradle:3.2.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
//添加下面两句,进行配置
classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5'
classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7.3'
}
}
allprojects {
repositories {
google()
jcenter()
mavenCentral()
maven { url 'https://jitpack.io' }
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
settings.gradle | Gradle | include ':app', ':YCCustomTextLib'
include ':SuperTextLib'
| yangchong211/YCCustomText | 493 | 自定义文本控件,支持富文本,包含两种状态:编辑状态和预览状态。编辑状态中,可以对插入本地或者网络图片,可以同时插入多张有序图片和删除图片,支持图文混排,并且可以对文字内容简单操作加粗字体,设置字体下划线,支持设置文字超链接(超链接支持跳转),已经用于多个实际项目中…… | Java | yangchong211 | 杨充 | Tencent |
android/build.gradle | Gradle | group 'com.utils.yc_flutter_utils'
version '1.0'
buildscript {
ext.kotlin_version = '1.3.50'
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.5.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
rootProject.allprojects {
repositories {
google()
jcenter()
}
}
apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
android {
compileSdkVersion 29
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
defaultConfig {
minSdkVersion 16
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.annotation:annotation:1.1.0'
implementation 'androidx.cardview:cardview:1.0.0'
//implementation files('lib/flutter.jar')
} | yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
android/settings.gradle | Gradle | rootProject.name = 'yc_flutter_utils'
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
android/src/main/java/com/utils/yc_flutter_utils/YcFlutterUtilsPlugin.java | Java | package com.utils.yc_flutter_utils;
import androidx.annotation.NonNull;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.PluginRegistry.Registrar;
/** YcFlutterUtilsPlugin */
public class YcFlutterUtilsPlugin implements FlutterPlugin, MethodCallHandler {
/// The MethodChannel that will the communication between Flutter and native Android
///
/// This local reference serves to register the plugin with the Flutter Engine and unregister it
/// when the Flutter Engine is detached from the Activity
private MethodChannel channel;
@Override
public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
channel = new MethodChannel(flutterPluginBinding.getFlutterEngine().getDartExecutor(), "yc_flutter_utils");
channel.setMethodCallHandler(this);
}
// This static function is optional and equivalent to onAttachedToEngine. It supports the old
// pre-Flutter-1.12 Android projects. You are encouraged to continue supporting
// plugin registration via this function while apps migrate to use the new Android APIs
// post-flutter-1.12 via https://flutter.dev/go/android-project-migration.
//
// It is encouraged to share logic between onAttachedToEngine and registerWith to keep
// them functionally equivalent. Only one of onAttachedToEngine or registerWith will be called
// depending on the user's project. onAttachedToEngine or registerWith must both be defined
// in the same class.
public static void registerWith(Registrar registrar) {
final MethodChannel channel = new MethodChannel(registrar.messenger(), "yc_flutter_utils");
channel.setMethodCallHandler(new YcFlutterUtilsPlugin());
}
@Override
public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
if (call.method.equals("getPlatformVersion")) {
result.success("Android " + android.os.Build.VERSION.RELEASE);
} else {
result.notImplemented();
}
}
@Override
public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
channel.setMethodCallHandler(null);
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
example/android/app/build.gradle | Gradle | def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}
def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}
def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '1'
}
def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
flutterVersionName = '1.0'
}
apply plugin: 'com.android.application'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
android {
compileSdkVersion 28
lintOptions {
disable 'InvalidPackage'
}
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.utils.yc_flutter_utils_example"
minSdkVersion 16
targetSdkVersion 28
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
}
buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig signingConfigs.debug
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
flutter {
source '../..'
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
example/android/app/src/main/java/com/utils/yc_flutter_utils_example/MainActivity.java | Java | package com.utils.yc_flutter_utils_example;
import io.flutter.embedding.android.FlutterActivity;
public class MainActivity extends FlutterActivity {
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
example/android/build.gradle | Gradle | buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.5.0'
}
}
allprojects {
repositories {
google()
jcenter()
}
}
rootProject.buildDir = '../build'
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
project.evaluationDependsOn(':app')
}
task clean(type: Delete) {
delete rootProject.buildDir
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
example/android/settings.gradle | Gradle | include ':app'
def localPropertiesFile = new File(rootProject.projectDir, "local.properties")
def properties = new Properties()
assert localPropertiesFile.exists()
localPropertiesFile.withReader("UTF-8") { reader -> properties.load(reader) }
def flutterSdkPath = properties.getProperty("flutter.sdk")
assert flutterSdkPath != null, "flutter.sdk not set in local.properties"
apply from: "$flutterSdkPath/packages/flutter_tools/gradle/app_plugin_loader.gradle"
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
example/android/settings_aar.gradle | Gradle | include ':app'
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
example/ios/Runner/AppDelegate.h | C/C++ Header | #import <Flutter/Flutter.h>
#import <UIKit/UIKit.h>
@interface AppDelegate : FlutterAppDelegate
@end
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
example/ios/Runner/AppDelegate.m | Objective-C | #import "AppDelegate.h"
#import "GeneratedPluginRegistrant.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[GeneratedPluginRegistrant registerWithRegistry:self];
// Override point for customization after application launch.
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
@end
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
example/ios/Runner/main.m | Objective-C | #import <Flutter/Flutter.h>
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
int main(int argc, char* argv[]) {
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
example/lib/main.dart | Dart | import 'package:flutter/material.dart';
import 'package:yc_flutter_utils/i18/localizations.dart';
import 'package:yc_flutter_utils/i18/template_time.dart';
import 'package:yc_flutter_utils/sp/sp_utils.dart';
import 'package:yc_flutter_utils/utils/flutter_init_utils.dart';
import 'package:yc_flutter_utils/except/handle_exception.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:yc_flutter_utils/log/log_utils.dart';
import 'package:yc_flutter_utils_example/utils/bus_utils_page.dart';
import 'package:yc_flutter_utils_example/utils/byte_utils_page.dart';
import 'package:yc_flutter_utils_example/utils/color_utils_page.dart';
import 'package:yc_flutter_utils_example/utils/data_utils_page.dart';
import 'package:yc_flutter_utils_example/utils/encrypt_utils_page.dart';
import 'package:yc_flutter_utils_example/utils/extension_utils_page.dart';
import 'package:yc_flutter_utils_example/utils/file_utils_page.dart';
import 'package:yc_flutter_utils_example/utils/get_it_page.dart';
import 'package:yc_flutter_utils_example/utils/i18_utils_page.dart';
import 'package:yc_flutter_utils_example/utils/image_utils_page.dart';
import 'package:yc_flutter_utils_example/utils/json_utils_page.dart';
import 'package:yc_flutter_utils_example/utils/log_utils_page.dart';
import 'package:yc_flutter_utils_example/utils/num_utils_page.dart';
import 'package:yc_flutter_utils_example/utils/object_utils_page.dart';
import 'package:yc_flutter_utils_example/utils/other_utils_page.dart';
import 'package:yc_flutter_utils_example/utils/parser_utils_page.dart';
import 'package:yc_flutter_utils_example/utils/regex_utils_page.dart';
import 'package:yc_flutter_utils_example/utils/screen_utils_page.dart';
import 'package:yc_flutter_utils_example/utils/sp_utils_page.dart';
import 'package:yc_flutter_utils_example/utils/storage_utils_page.dart';
import 'package:yc_flutter_utils_example/utils/system_utils_page.dart';
import 'package:yc_flutter_utils_example/utils/text_utils_page.dart';
import 'package:yc_flutter_utils_example/utils/timer_utils_page.dart';
import 'package:yc_flutter_utils_example/widget/custom_raised_button.dart';
void main() {
//初始化工具类操作
Future(() async {
await FlutterInitUtils.fetchInitUtils();
});
AppLocalizations.supportedLocales = [
const Locale('en', 'US'),
const Locale('pt', 'BR'),
const Locale('ja', 'JP'),
const Locale('zh', 'CN'),
];
//区分格式化时间
TemplateTime.dateFormat2 = {
"en_US": "MM-dd-yyyy",
"pt_BR": "dd-MM-yyyy",
"ja_JP": "yyyy/MM/dd",
"zh_CN": "yyyy年MM月dd日",
};
//比如:zh_CN,表示中国
//languageCode就是:zh
//countryCode就是:CN
//Locale myLocale = Localizations.localeOf(context);
LocalizationTime.locale = new Locale("zh","CN");
Future(() async {
await SpUtils.init();
});
//await FlutterInitUtils.fetchInitUtils();
//FlutterInitUtils.fetchInitUtils();
//runApp(MainApp());
hookCrash(() {
runApp(MainApp());
});
}
class MainApp extends StatelessWidget{
//在构建页面时,会调用组件的build方法
//widget的主要工作是提供一个build()方法来描述如何构建UI界面
//通常是通过组合、拼装其它基础widget
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new HomePage(title: 'Flutter常用工具类'),
);
}
}
//StatelessWidget表示组件,一切都是widget,可以理解为组件
//有状态的组件(Stateful widget)
//无状态的组件(Stateless widget)
//Stateful widget可以拥有状态,这些状态在widget生命周期中是可以变的,而Stateless widget是不可变的
class HomePage extends StatefulWidget{
HomePage({Key key, this.title}) : super(key: key);
final String title;
//createState()来创建状态(State)对象
@override
State<StatefulWidget> createState() {
return new HomePageState();
}
}
class HomePageState extends State<HomePage>{
@override
void initState() {
super.initState();
LogUtils.init(tag : "yc",isDebug: true , maxLen: 128);
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
}
@override
void deactivate() {
super.deactivate();
}
@override
void dispose() {
super.dispose();
}
//在构建页面时,会调用组件的build方法
//widget的主要工作是提供一个build()方法来描述如何构建UI界面
//通常是通过组合、拼装其它基础widget
@override
Widget build(BuildContext context) {
return MaterialApp(
// 本地化的代理类
localizationsDelegates: [
const AppLocalizationsDelegate(),
// 本地化的代理类
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
//支持的语言
supportedLocales: AppLocalizations.supportedLocales,
home: Scaffold(
appBar: new AppBar(
title: new Text(this.widget.title),
),
body: new Center(
child: new ListView(
children: <Widget>[
CustomRaisedButton(new BusPage(), "EventBus 事件通知工具类"),
CustomRaisedButton(new GetItPage(), "serviceLocator测试"),
CustomRaisedButton(new LogUtilsPage(), "LogUtils 日志工具类"),
CustomRaisedButton(new DatePage(), "DateUtils 日期工具类"),
CustomRaisedButton(new JsonUtilsPage(), "JsonUtils Json工具类"),
CustomRaisedButton(new FileStoragePage(), "FileUtils 文件工具类"),
CustomRaisedButton(new EncryptPage(), "EncryptUtils 加解密工具类"),
CustomRaisedButton(new ObjectPage(), "ObjectUtils Object工具类"),
CustomRaisedButton(new TextPage(), "TextUtils 文本工具类"),
CustomRaisedButton(new ScreenPage(), "ScreenUtils 屏幕工具类"),
CustomRaisedButton(new I18Page(), "I18 国际化工具类"),
CustomRaisedButton(new NumPage(), "NumUtils 格式处理工具类"),
CustomRaisedButton(new ColorPage(), "ColorUtils 颜色工具类"),
CustomRaisedButton(new ImagePage(), "ImageUtils 图片工具类"),
CustomRaisedButton(new TimerPage(), "TimerUtils 计时器工具类"),
CustomRaisedButton(new RegexPage(), "RegexUtils 正则校验工具类"),
CustomRaisedButton(new StoragePage(), "StorageUtils 文件管理工具类"),
CustomRaisedButton(new ExtensionPage(), "extension_xx 拓展工具类"),
CustomRaisedButton(new SpPage(), "SpUtils sp存储工具类"),
CustomRaisedButton(new ParserPage(), "MarkupUtils 解析xml/html工具类"),
CustomRaisedButton(new SystemPage(), "SystemUtils 系统工具类"),
CustomRaisedButton(new BytePage(), "Byte 字节工具类"),
CustomRaisedButton(new OtherPage(), "其他一些工具类"),
],
),
),
),
);
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
example/lib/model/city.dart | Dart | import 'package:json_annotation/json_annotation.dart';
part 'city.g.dart';
@JsonSerializable()
class City extends Object {
@JsonKey(name: 'name')
String name;
City(this.name,);
factory City.fromJson(Map<String, dynamic> srcJson) => _$CityFromJson(srcJson);
Map<String, dynamic> toJson() => _$CityToJson(this);
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
example/lib/model/city.g.dart | Dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'city.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
City _$CityFromJson(Map<String, dynamic> json) {
return City(
json['name'] as String,
);
}
Map<String, dynamic> _$CityToJson(City instance) => <String, dynamic>{
'name': instance.name,
};
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
example/lib/utils/bus_utils_page.dart | Dart |
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:yc_flutter_utils/bus/event_bus_helper.dart';
import 'package:yc_flutter_utils/bus/event_bus_service.dart';
class BusPage extends StatefulWidget {
BusPage();
@override
State<StatefulWidget> createState() {
return new _DatePageState();
}
}
class _DatePageState extends State<BusPage> {
String message1 = "124321423";
String message2 = "1243.21423";
StreamSubscription _subscription;
@override
void initState() {
super.initState();
registerBus();
registerBus2();
}
@override
void dispose() {
super.dispose();
unRegisterBus();
unRegisterBus2();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: new AppBar(
title: new Text("DateUtils工具类"),
centerTitle: true,
),
body: new Column(
children: <Widget>[
new Text("接收bus消息1 :$message1"),
MaterialButton(
onPressed: sendBus1,
child: new Text("发送bus消息1"),
color: Colors.cyan,
),
new Text("接收bus消息2 :$message2"),
MaterialButton(
onPressed: sendBus2,
child: new Text("发送bus消息2"),
color: Colors.cyan,
),
],
),
);
}
void sendBus1() {
EventBusService.instance.eventBus.fire(EventMessage(
"eventBus1",
arguments: {"busMessage": "发送bus消息1"},
));
}
void registerBus() {
_subscription = EventBusService.instance.eventBus.on<EventMessage>().listen((event) {
String name = event.eventName;
//前后台切换发生了变化
if (name == "eventBus1") {
var busMessage = event.arguments["busMessage"];
setState(() {
message1 = busMessage;
});
}
});
}
unRegisterBus(){
if (_subscription != null) {
_subscription.cancel();
_subscription = null;
}
}
///------------------------------------------------------------------
void sendBus2() {
var arg = "发送bus消息1";
bus.emit("eventBus2", arg);
}
void registerBus2() {
bus.on("eventBus2", (arg) {
var busMessage = arg;
setState(() {
message2 = "接收消息:" + busMessage;
});
});
}
unRegisterBus2(){
bus.off("eventBus2", (arg) {
});
}
} | yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
example/lib/utils/byte_utils_page.dart | Dart |
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:yc_flutter_utils/byte/byte.dart';
import 'package:yc_flutter_utils/byte/byte_array.dart';
import 'package:yc_flutter_utils/byte/byte_double_word.dart';
import 'package:yc_flutter_utils/byte/byte_utils.dart';
import 'package:yc_flutter_utils/byte/byte_word.dart';
class BytePage extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return new _PageState();
}
}
class _PageState extends State<BytePage> {
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: new AppBar(
title: new Text("ByteUtils 字节工具类"),
centerTitle: true,
),
body: Center(child: WidgetExample()),
);
}
}
class WidgetExample extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new ListView(
children: [
MaterialButton(
onPressed: testFromReadable,
child: new Text("转换int值为二进制"),
color: Colors.cyan,
),
MaterialButton(
onPressed: testToReadable,
child: new Text("将字节数组转换为可读字符串"),
color: Colors.cyan,
),
MaterialButton(
onPressed: testToBase64,
child: new Text("将字节数组转换为base64字符串"),
color: Colors.cyan,
),
MaterialButton(
onPressed: testFromBase64,
child: new Text("转换base64字符串到字节数组"),
color: Colors.cyan,
),
MaterialButton(
onPressed: testClone,
child: new Text("克隆字节数组"),
color: Colors.cyan,
),
MaterialButton(
onPressed: testSame,
child: new Text("判断两个字节是否相同"),
color: Colors.cyan,
),
MaterialButton(
onPressed: testExtract,
child: new Text("从字节序列中提取数据"),
color: Colors.cyan,
),
MaterialButton(
onPressed: testByteArrayContructor,
child: new Text("字节数组处理"),
color: Colors.cyan,
),
MaterialButton(
onPressed: testByteClass,
child: new Text("ByteClass"),
color: Colors.cyan,
),
],
);
}
void testFromReadable() {
const str1 = '01 02, ff 0x10,0xfa , 90 76 AF a0';
Uint8List bytes1 = ByteUtils.fromReadable(str1);
// [1, 2, 255, 16, 250, 144, 118, 175, 160]
print(bytes1.toString());
const str2 = '101 02 90 01,33 90 76 102, 901';
final bytes2 = ByteUtils.fromReadable(str2, radix: Radix.dec);
// [101, 2, 90, 1, 33, 90, 76, 102, 133]
print(bytes2);
Uint8List bytes3 = ByteUtils.fromReadable("a8");
print(bytes3.toString());
}
void testToReadable() {
final bytes = Uint8List.fromList([0x80, 01, 02, 0xff, 0xA1, 30, 10, 20, 77]);
final str1 = ByteUtils.toReadable(bytes);
// 0x80 0x1 0x2 0xFF 0xA1 0x1E 0xA 0x14 0x4D
print(str1);
final str2 = ByteUtils.toReadable(bytes, radix: Radix.dec);
// 128 1 2 255 161 30 10 20 77
print(str2);
final bytes3 = Uint8List.fromList([0x80]);
final str3 = ByteUtils.toReadable(bytes3);
print(str3);
}
void testToBase64() {
final bytes = Uint8List.fromList([0x80, 01, 02, 0xff, 0xA1, 30, 10, 32]);
final base64 = ByteUtils.toBase64(bytes);
// gAEC/6EeCiA=
print(base64);
}
void testFromBase64() {
final base64 = 'gAEC/6EeCiA=';
final bytes = ByteUtils.fromBase64(base64);
// [128, 1, 2, 255, 161, 30, 10, 32]
print(bytes);
}
void testClone() {
final bytes = Uint8List.fromList([0x80, 01, 02, 0xff, 0xA1, 30, 10, 32]);
final clone = ByteUtils.clone(bytes);
// [128, 1, 2, 255, 161, 30, 10, 32]
print(clone);
}
void testSame() {
final bytes1 = Uint8List.fromList([0x80, 01, 02, 0xff, 0xA1, 30, 10, 32]);
final bytes2 = Uint8List.fromList([0xA1, 30, 10, 32]);
final same = ByteUtils.same(bytes1, bytes2);
// false
print(same);
}
void testExtract() {
final bytes = Uint8List.fromList([0x80, 01, 02, 0xff, 0xA1, 30, 10, 32]);
// 0x1 0x2 0xFF
print(ByteUtils.toReadable(
ByteUtils.extract(origin: bytes, indexStart: 1, length: 3)));
// null
print(ByteUtils.toReadable(
ByteUtils.extract(origin: bytes, indexStart: 0, length: 0)));
// 0x80 0x1 0x2 0xFF 0xA1 0x1E 0xA 0x20
print(ByteUtils.toReadable(
ByteUtils.extract(origin: bytes, indexStart: 0, length: 100)));
// null
print(ByteUtils.toReadable(
ByteUtils.extract(origin: bytes, indexStart: 10, length: 8)));
// 0x80 0x1 0x2 0xFF 0xA1 0x1E 0xA 0x20
print(ByteUtils.toReadable(
ByteUtils.extract(origin: bytes, indexStart: 0, length: 8)));
// null
print(ByteUtils.toReadable(
ByteUtils.extract(origin: bytes, indexStart: 8, length: 1)));
// 0x20
print(ByteUtils.toReadable(
ByteUtils.extract(origin: bytes, indexStart: 7, length: 1)));
}
void testByteArrayContructor() {
// [1, 2, 3]
final arr1 = ByteArray(Uint8List.fromList([1, 2, 3]));
print(arr1.bytes);
// [3]
final arr2 = ByteArray.fromByte(3);
print(arr2.bytes);
// [1, 2, 3, 4, 5, 6]
final arr3 = ByteArray.combineArrays(
Uint8List.fromList([1, 2, 3]), Uint8List.fromList([4, 5, 6]));
print(arr3.bytes);
// [1, 2, 3, 7]
final arr4 = ByteArray.combine1(Uint8List.fromList([1, 2, 3]), 7);
print(arr4.bytes);
// [8, 1, 2, 3]
final arr5 = ByteArray.combine2(8, Uint8List.fromList([1, 2, 3]));
print(arr5.bytes);
// [8, 1, 2, 3, 10]
arr5.append(10);
print(arr5.bytes);
// [8, 1, 2, 3, 10, 9, 9]
arr5.appendArray(Uint8List.fromList([9, 9]));
print(arr5.bytes);
// [8, 12, 1, 2, 3, 10, 9, 9]
arr5.insert(indexStart: 1, value: 12);
print(arr5.bytes);
// [8, 12, 1, 2, 3, 10, 9, 9, 13]
arr5.insert(indexStart: 100, value: 13);
print(arr5.bytes);
// [8, 12, 1, 23, 23, 2, 3, 10, 9, 9, 13]
arr5.insertArray(indexStart: 3, arrayInsert: Uint8List.fromList([23, 23]));
print(arr5.bytes);
// [12, 1, 23, 23, 2, 3, 10, 9, 9, 13]
arr5.remove(indexStart: 0, lengthRemove: 1);
print(arr5.bytes);
// [12, 1, 23]
arr5.remove(indexStart: 3, lengthRemove: 9);
print(arr5.bytes);
}
void testByteClass() {
final byte1 = Byte(3);
final byte2 = Byte(0xA1);
final byte3 = Byte(12);
final byte4 = Byte(65);
// 03
print(byte1);
final word = ByteWord(high: byte2, low: byte1);
// A1,03
print(word);
final doubleWord =
ByteDoubleWord(one: byte1, two: byte2, three: byte3, four: byte4);
// 41,0C,A1,03
print(doubleWord);
final dw = ByteDoubleWord.fromInt(184384451);
// 0x0A,0xFD,0x7B,0xC3
print(dw);
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
example/lib/utils/color_utils_page.dart | Dart |
import 'package:flutter/material.dart';
import 'package:yc_flutter_utils/color/color_utils.dart';
import 'package:yc_flutter_utils/date/data_formats.dart';
import 'package:yc_flutter_utils/date/date_utils.dart';
import 'package:yc_flutter_utils/encrypt/encrypt_utils.dart';
import 'package:yc_flutter_utils/object/object_utils.dart';
class ColorPage extends StatefulWidget {
ColorPage();
@override
State<StatefulWidget> createState() {
return new _PageState();
}
}
class _PageState extends State<ColorPage> {
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: new AppBar(
title: new Text("ColorUtils 颜色工具类"),
centerTitle: true,
),
body: new Column(
children: <Widget>[
new Text("hexToColor转化1:",
style: new TextStyle(
color: ColorUtils.hexToColor('#A357D6'),
),
),
new Text("将颜色转化为color1:",
style: new TextStyle(
color: ColorUtils.toColor('#FF6325'),
),
),
new Text("hexToColor转化1:",
style: new TextStyle(
color: ColorUtils.hexToColor('#50A357D6'),
),
),
new Text("将颜色转化为color1:",
style: new TextStyle(
color: ColorUtils.toColor('#50FF6325'),
),
),
new Text("hexToColor转化2,错误格式:",
style: new TextStyle(
color: ColorUtils.hexToColor('#E5E5E81'),
),
),
new Text("将颜色转化为color2,错误格式:",
style: new TextStyle(
color: ColorUtils.toColor('#E5E5E11'),
),
),
new Text("将color颜色转变为字符串:" + ColorUtils.colorString(Colors.brown),
),
new Text("检查字符串是否为十六进制:" + ColorUtils.isHexadecimal("#E5E5E8").toString()),
new Text("检查字符串是否为十六进制:" + ColorUtils.isHexadecimal("#E52E5E81").toString()),
new Text("检查字符串是否为十六进制:" + ColorUtils.isHexadecimal("#E52E5E811").toString()),
],
),
);
}
} | yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
example/lib/utils/data_utils_page.dart | Dart |
import 'package:flutter/material.dart';
import 'package:yc_flutter_utils/date/data_formats.dart';
import 'package:yc_flutter_utils/date/date_utils.dart';
class DatePage extends StatefulWidget {
DatePage();
@override
State<StatefulWidget> createState() {
return new _DatePageState();
}
}
class _DatePageState extends State<DatePage> {
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
DateTime dateTime = new DateTime.now();
return Scaffold(
appBar: new AppBar(
title: new Text("DateUtils工具类"),
centerTitle: true,
),
body: new Column(
children: <Widget>[
new Text("获取当前毫秒值:" + DateUtils.getNowDateMs().toString()),
new Text("获取现在日期字符串:" + DateUtils.getNowDateString().toString()),
new Text("获取当前日期返回DateTime(utc):" + DateUtils.getNowUtcDateTime().toString()),
new Text("获取当前日期,返回指定格式:" + DateUtils.getNowDateTimeFormat(DateFormats.PARAM_FULL).toString()),
new Text("获取当前日期,返回指定格式:" + DateUtils.getUtcDateTimeFormat(DateFormats.PARAM_Y_M_D_H_M).toString()),
new Text("格式化日期 DateTime:" + DateUtils.formatDate(dateTime)),
new Text("格式化日期 DateTime:" + DateUtils.formatDate(dateTime,format: DateFormats.Y_M_D_H_M)),
new Text("格式化日期字符串:" + DateUtils.formatDateString('2021-07-18 16:03:10', format: "yyyy/M/d HH:mm:ss")),
new Text("格式化日期字符串:" + DateUtils.formatDateString('2021-07-18 16:03:10', format: "yyyy/M/d HH:mm:ss")),
new Text("格式化日期毫秒时间:" + DateUtils.formatDateMilliseconds(1213423143312, format: "yyyy/M/d HH:mm:ss")),
new Text("获取dateTime是星期几:" + DateUtils.getWeekday(dateTime)),
new Text("获取毫秒值对应是星期几:" + DateUtils.getWeekdayByMilliseconds(1213423143312)),
new Text("根据时间戳判断是否是今天:" + DateUtils.isToday(1213423143312).toString()),
new Text("根据时间戳判断是否是今天:" + DateUtils.isToday(dateTime.millisecondsSinceEpoch).toString()),
new Text("根据时间判断是否是昨天:" + DateUtils.isYesterday(dateTime,dateTime).toString()),
new Text("根据时间戳判断是否是本周:" + DateUtils.isWeek(1213423143312).toString()),
new Text("根据时间戳判断是否是本周:" + DateUtils.isWeek(1213423143312).toString()),
new Text("根据时间戳判断是否是本周:" + DateUtils.isWeek(1213423143312).toString()),
new Text("是否是闰年:" + DateUtils.isLeapYear(dateTime).toString()),
new Text("是否是闰年:" + DateUtils.isLeapYearByMilliseconds(1213423143312).toString()),
],
),
);
}
} | yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
example/lib/utils/encrypt_utils_page.dart | Dart |
import 'package:flutter/material.dart';
import 'package:yc_flutter_utils/date/data_formats.dart';
import 'package:yc_flutter_utils/date/date_utils.dart';
import 'package:yc_flutter_utils/encrypt/encrypt_utils.dart';
class EncryptPage extends StatefulWidget {
EncryptPage();
@override
State<StatefulWidget> createState() {
return new _PageState();
}
}
class _PageState extends State<EncryptPage> {
String string = "yangchong";
String key = '11, 22, 33, 44, 55, 66';
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
var encodeBase64 = EncryptUtils.encodeBase64(string);
var encodeBase642 = EncryptUtils.decodeBase64(encodeBase64);
String encode = EncryptUtils.xorBase64Encode(string, key);
String decode = EncryptUtils.xorBase64Decode(encode, key);
return Scaffold(
appBar: new AppBar(
title: new Text("EncryptUtils 加解密工具类"),
centerTitle: true,
),
body: new Column(
children: <Widget>[
new Text("md5 加密:" + EncryptUtils.encodeMd5(string)),
new Text("Base64加密:" + encodeBase64),
new Text("Base64解密:" + encodeBase642),
new Text("异或对称 Base64 加密:" + encode),
new Text("异或对称 Base64 解密:" + decode),
],
),
);
}
} | yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
example/lib/utils/extension_utils_page.dart | Dart |
import 'package:flutter/material.dart';
import 'package:yc_flutter_utils/extens/extension_int.dart';
import 'package:yc_flutter_utils/extens/extension_list.dart';
import 'package:yc_flutter_utils/extens/extension_map.dart';
import 'package:yc_flutter_utils/num/num_utils.dart';
class ExtensionPage extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return new _DatePageState();
}
}
class _DatePageState extends State<ExtensionPage> {
String str1 = "124321423";
String str2 = "1243.21423";
double d = 12312.3121;
double d2 = 12312.3121;
int a1 = 1881;
int a2 = 25;
List<dynamic> list = new List();
Map map = new Map();
@override
void initState() {
super.initState();
list.add("1");
list.add(100);
list.add("yangchong");
list.add(13.14);
list.add("doubi");
map["1"] = "yc";
map["2"] = "doubi";
map["3"] = 1;
map["4"] = 2.5;
}
@override
Widget build(BuildContext context) {
DateTime dateTime = new DateTime.now();
return Scaffold(
appBar: new AppBar(
title: new Text("DateUtils工具类"),
centerTitle: true,
),
body: new Column(
children: <Widget>[
new Text("检查int是否为回文:" + a2.isPalindrome().toString()),
new Text("检查所有数据是否具有相同的值:" + a1.isOneAKind().toString()),
new Text("转换int值为二进制:" + a1.toBinary().toString()),
new Text("转换int值为二进制int:" + a1.toBinaryInt().toString()),
new Text("转换int值为二进制字符串:" + a1.fromBinary().toString()),
new Text("将list转化为json字符串:" + list.toJsonString().toString()),
new Text("将list转化为json字符串:" + list.getJsonPretty().toString()),
//new Text("获取num列表的总值(int/double):" + list.valueTotal().toString()),
new Text("判断对象是否为null:" + list.isNull().toString()),
new Text("检查数据是否为空或空(空或只包含空格):" + list.isNullOrBlank().toString()),
new Text("将map转化为json字符串:" + map.toJsonString().toString()),
new Text("将map转化为json字符串换行:" + map.getJsonPretty().toString()),
new Text("检查数据是否为空或空:" + map.isNull().toString()),
new Text("检查数据是否为空或空:" + map.isNullOrBlank().toString()),
new Text("将数字字符串转int:" + NumUtils.getIntByValueString("yangchong").toString()),
new Text("数字字符串转double:" + NumUtils.getDoubleByValueString(str2).toString()),
new Text("数字保留x位小数:" + NumUtils.getNumByValueString(str2,fractionDigits: 2).toString()),
new Text("浮点数字保留x位小数:" + NumUtils.getNumByValueDouble(d,2).toString()),
new Text("浮点数字保留x位小数:" + NumUtils.getNumByValueDouble(d,2).toString()),
new Text("判断是否是否是0:" + NumUtils.isZero(d).toString()),
],
),
);
}
} | yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
example/lib/utils/file_utils_page.dart | Dart | import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:yc_flutter_utils/file/file_utils.dart';
class FileStoragePage extends StatefulWidget {
@override
State<StatefulWidget> createState() => StorageState();
}
class StorageState extends State<FileStoragePage> {
bool isSuccess1 = false;
String string1 = "null";
bool isSuccess2 = false;
String string2 = "null";
bool isSuccess3 = false;
String string3 = "null";
bool isSuccess4 = false;
String string4 = "null";
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('FileUtils 文件工具类'),
),
body: new ListView(
children: <Widget>[
new Text("存储json文件1,状态 :$isSuccess1"),
MaterialButton(
onPressed: save1,
child: new Text("存储json文件"),
color: Colors.cyan,
),
new Text("获取json文件1,状态 :$string1"),
MaterialButton(
onPressed: get1,
child: new Text("获取json文件"),
color: Colors.cyan,
),
MaterialButton(
onPressed: clear1,
child: new Text("清除json文件"),
color: Colors.cyan,
),
new Text("存储json文件2,状态 :$isSuccess2"),
MaterialButton(
onPressed: save2,
child: new Text("存储json文件2"),
color: Colors.cyan,
),
new Text("获取json文件2,状态 :$string2"),
MaterialButton(
onPressed: get2,
child: new Text("获取json文件2"),
color: Colors.cyan,
),
new Text("存储字符串文件1,状态 :$isSuccess3"),
MaterialButton(
onPressed: save3,
child: new Text("存储字符串文件"),
color: Colors.cyan,
),
new Text("获取字符串文件1,状态 :$string3"),
MaterialButton(
onPressed: get3,
child: new Text("获取字符串文件"),
color: Colors.cyan,
),
new Text("存储字符串文件2,状态 :$isSuccess4"),
MaterialButton(
onPressed: save4,
child: new Text("存储字符串文件2"),
color: Colors.cyan,
),
new Text("获取字符串文件2,状态 :$string4"),
MaterialButton(
onPressed: get4,
child: new Text("获取字符串文件2"),
color: Colors.cyan,
),
],
),
);
}
void save1() {
var mapHeatModel = new MapHeatModel();
mapHeatModel.version = "100";
List<MapPositionModel> focusCenter = new List();
for(int i=0 ; i<2 ; i++){
MapPositionModel model = new MapPositionModel();
model.lng = i.toDouble();
model.lat = i.toDouble();
focusCenter.add(model);
}
mapHeatModel.focusCenter = focusCenter;
var encode = mapHeatModel.encode();
var future = FileUtils.writeJsonFileDir(encode, "map1.json");
setState(() {
if(future == null){
isSuccess1 = false;
} else {
isSuccess1 = true;
}
});
}
void get1() {
FileUtils.readStringDir("map1.json").then((value){
setState(() {
string1 = value;
});
});
}
void clear1() {
FileUtils.clearFileDataDir("map1.json").then((value){
setState(() {
isSuccess1 = value;
});
});
}
void save2() async{
var mapHeatModel = new MapHeatModel();
mapHeatModel.version = "100";
List<MapPositionModel> focusCenter = new List();
for(int i=0 ; i<2 ; i++){
MapPositionModel model = new MapPositionModel();
model.lng = i.toDouble();
model.lat = i.toDouble();
focusCenter.add(model);
}
mapHeatModel.focusCenter = focusCenter;
var encode = mapHeatModel.encode();
String appDocDir = await FileUtils.getAppDocDir();
String filePath = appDocDir + '/map2.json';
var future = FileUtils.writeJsonCustomFile(encode,filePath);
setState(() {
if(future == null){
isSuccess2 = false;
} else {
isSuccess2 = true;
}
});
}
void get2() async{
String appDocDir = await FileUtils.getAppDocDir();
String filePath = appDocDir + '/map2.json';
FileUtils.readStringCustomFile(filePath).then((value){
setState(() {
string2 = value;
});
});
}
void save3() async{
var future = FileUtils.writeStringDir("fadsfadsfasd","map3.txt");
setState(() {
if(future == null){
isSuccess3 = false;
} else {
isSuccess3 = true;
}
});
}
void get3() async{
FileUtils.readStringDir("map3.txt").then((value){
setState(() {
string3 = value;
});
});
}
void save4() async{
String appDocDir = await FileUtils.getAppDocDir();
String filePath = appDocDir + '/map4.txt';
var future = FileUtils.writeStringFile("dfadsfadsfdswe32",filePath);
setState(() {
if(future == null){
isSuccess4 = false;
} else {
isSuccess4 = true;
}
});
}
void get4() async{
String appDocDir = await FileUtils.getAppDocDir();
String filePath = appDocDir + '/map4.txt';
FileUtils.readStringCustomFile(filePath).then((value){
setState(() {
string4 = value;
});
});
}
}
class MapHeatModel{
String version;
List<MapPositionModel> focusCenter;
Object encode() {
final Map<String, dynamic> ret = <String, dynamic>{};
ret['version'] = version;
ret['focusCenter'] = focusCenter?.map((e) => e?.encode())?.toList();
return ret;
}
static MapHeatModel decode(Object message){
if (message == null) return null;
final Map<dynamic, dynamic> rawMap = message as Map<dynamic, dynamic>;
final Map<String, dynamic> map = Map.from(rawMap);
return MapHeatModel()
..version = map['version'] == null
?null
:map['version'] as String
..focusCenter = map['focusCenter'] == null
?[]
:List.from(map['focusCenter'])
?.map((e) => e == null
? null
: MapPositionModel.decode(e))
?.toList()
;
}
}
class MapPositionModel {
double lat;
double lng;
Object encode() {
final Map<String, dynamic> ret = <String, dynamic>{};
ret['lat'] = lat;
ret['lng'] = lng;
return ret;
}
static MapPositionModel decode(Object message){
if (message == null) return null;
final Map<dynamic, dynamic> rawMap = message as Map<dynamic, dynamic>;
final Map<String, dynamic> map = Map.from(rawMap);
return MapPositionModel()
..lat = map['lat'] == null
?0.0
:map['lat'] as double
..lng = map['lng'] == null
?0.0
:map['lng'] as double
;
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
example/lib/utils/get_it_page.dart | Dart | import 'package:flutter/material.dart';
import 'package:yc_flutter_utils/locator/get_it.dart';
import 'package:yc_flutter_utils/locator/get_it_helper.dart';
import 'package:yc_flutter_utils/log/log_utils.dart';
class GetItPage extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return new GetItState();
}
}
class GetItState extends State<GetItPage>{
String title = "初始化值";
GetItLocator getItLocator;
@override
void initState() {
super.initState();
if(getItLocator==null){
getItLocator = new GetItLocator();
getItLocator.register();
}
}
@override
void dispose() {
super.dispose();
if(getItLocator!=null){
getItLocator.reset();
}
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(title: new Text("测试getIt的功能")),
body: ListView(
children: <Widget>[
new Text("测试GetItHelper的功能,ServiceLocator,将类与依赖解耦,让类在编译的时候并知道依赖相的具体实现。从而提升其隔离性"),
new Text(title),
RaisedButton(
onPressed: () {
var businessService = getItLocator.get();
var noneBusinessPattern = businessService.noneBusinessPattern();
setState(() {
title = noneBusinessPattern+ "---使用GetItHelper";
});
},
color: const Color(0xffff0000),
child: new Text('使用GetItHelper,获取接口的子类数据'),
),
RaisedButton(
onPressed: () {
var businessService = getItLocator.get();
var noneBusinessPattern = businessService.noneBusinessPattern();
setState(() {
title = noneBusinessPattern + "---使用GetIt";
});
},
color: const Color(0xffff0000),
child: new Text('使用GetIt,获取接口的子类数据'),
),
RaisedButton(
onPressed: () {
// 注册地图资源服务
GetIt.I.registerLazySingleton<ResourceService>(() => ResourceManagerImpl());
// 注册后才能使用
ResourceService _resourceService = resourceService();
_resourceService.init();
var style = _resourceService.getStyle();
_resourceService.release();
setState(() {
title = "---使用GetIt调用ResourceService--"+style;
});
},
color: const Color(0xffff0000),
child: new Text('使用GetIt调用ResourceService'),
),
],
));
}
}
class GetItLocator{
//简单案例,方便分析代码原理
GetItHelper getIt = new GetItHelper();
GetIt serviceLocator = GetIt.instance;
void register(){
//注册模式状态管理service
getIt.registerSingleton<BusinessService>(new BusinessServiceImpl());
serviceLocator.registerLazySingleton<BusinessService>(() => BusinessServiceImpl());
}
void reset(){
getIt.reset();
//解绑操作
serviceLocator.resetLazySingleton<BusinessService>();
}
BusinessService get(){
var businessService = getIt<BusinessService>();
return businessService;
}
BusinessService getService(){
BusinessService businessService = serviceLocator<BusinessService>();
return businessService;
}
}
abstract class BusinessService {
//无业务模式
String noneBusinessPattern();
}
class BusinessServiceImpl extends BusinessService {
BusinessServiceImpl();
@override
String noneBusinessPattern() {
LogUtils.d("-----noneBusinessPattern");
return "获取子类的数据";
}
}
ResourceService Function() resourceService = () => GetIt.I.get<ResourceService>();
abstract class ResourceService {
///初始化数据
Future<void> init();
///释放
void release();
///获取样式
String getStyle();
}
class ResourceManagerImpl extends ResourceService{
@override
String getStyle() {
LogUtils.d("ResourceManagerImpl------getStyle");
return "getStyle";
}
@override
Future<void> init() {
LogUtils.d("ResourceManagerImpl------init");
}
@override
void release() {
LogUtils.e("ResourceManagerImpl------release");
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
example/lib/utils/i18_utils_page.dart | Dart |
import 'package:flutter/material.dart';
import 'package:yc_flutter_utils/date/date_utils.dart';
import 'package:yc_flutter_utils/i18/template_time.dart';
import 'package:yc_flutter_utils/i18/extension.dart';
class I18Page extends StatefulWidget {
I18Page();
@override
State<StatefulWidget> createState() {
return new _PageState();
}
}
class _PageState extends State<I18Page> {
String name = "初始化值";
String time1 = "";
String time2 = "";
@override
void initState() {
super.initState();
var dateTime = DateUtils.getNowDateMs();
time1 = LocalizationTime.getFormat1(dateTime);
time2 = LocalizationTime.getFormat2(dateTime);
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Localizations 国际化"),
),
body: new Center(
child: new Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
new Text(
"获取国际化,文本内容:" + context.getString("name"),
),
new Text(
"获取国际化,文本内容2:" + context.getString("work"),
),
new Text(
"获取国际化,时间格式 :" +time1,
style: new TextStyle(
fontSize: 18.0,
),
textDirection: TextDirection.rtl,
),
new Text(
"获取国际化,时间格式 :" +time2,
style: new TextStyle(
fontSize: 18.0,
),
textDirection: TextDirection.rtl,
),
],
),
));
}
} | yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
example/lib/utils/image_utils_page.dart | Dart |
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:yc_flutter_utils/date/data_formats.dart';
import 'package:yc_flutter_utils/date/date_utils.dart';
import 'package:yc_flutter_utils/encrypt/encrypt_utils.dart';
import 'package:yc_flutter_utils/image/image_utils.dart';
import 'package:yc_flutter_utils/object/object_utils.dart';
class ImagePage extends StatefulWidget {
ImagePage();
@override
State<StatefulWidget> createState() {
return new _PageState();
}
}
class _PageState extends State<ImagePage> {
String string = "yangchong";
List list1 = new List();
List list2 = null;
Map map1 = new Map();
Map map2 ;
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
list1.add("yangchong");
map1["name"] = "yangchong";
return Scaffold(
appBar: new AppBar(
title: new Text("EncryptUtils 加解密工具类"),
centerTitle: true,
),
body: new Column(
children: <Widget>[
ImageUtils.showNetImageWh("https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/586766ce5091479d9a10215141c51d13~tplv-k3u1fbpfcp-zoom-in-crop-mark:652:0:0:0.awebp",100,100),
ImageUtils.showNetImageWh("https://img-blog.csdnimg.cn/20201013094115174.png",200,200),
ImageUtils.showNetImageWhClip("https://img-blog.csdnimg.cn/20201013094115174.png",200,200,30),
ImageUtils.showNetImageCircle("https://img-blog.csdnimg.cn/20201013094115174.png",100),
],
),
);
}
}
class Base64Page extends StatefulWidget {
final String title = "base64";
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<Base64Page> {
// final picker = ImagePicker();
TextEditingController base64;
@override
void initState() {
base64 = TextEditingController(text: '');
super.initState();
}
@override
Widget build(BuildContext context) {
return Center(
child: Container(
child: Column(
children: [
MaterialButton(
onPressed: () async {
var pickedFile;
// await picker.getImage(source: ImageSource.gallery);
setState(() {
if (pickedFile != null) {
base64.text =
ImageUtils.fileToBase64(File(pickedFile.path));
} else {
print('No image selected.');
}
});
},
child: Text("Select Image")),
SizedBox(height: 10),
Text("Base64 String of selected image:${base64.text}"),
SizedBox(height: 30),
Text("Base64 to Image:"),
CircleAvatar(
radius: 25,
backgroundImage: ImageUtils.base64ToImage(base64.text),
),
],
),
),
);
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
example/lib/utils/json_utils_page.dart | Dart | import 'package:flutter/material.dart';
import 'package:yc_flutter_utils/json/json_utils.dart';
import 'package:yc_flutter_utils_example/model/city.dart';
class JsonUtilsPage extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return new JsonUtilsState();
}
}
class JsonUtilsState extends State<JsonUtilsPage>{
String title1 = "初始化值";
String title2 = "初始化值";
String title3 = "初始化值";
String title4 = "初始化值";
City city = new City("北京");
@override
void initState() {
super.initState();
}
@override
void dispose() {
super.dispose();
}
@override
Widget build(BuildContext context) {
String listStr = "[{\"name\":\"成都市\"}, {\"name\":\"北京市\"}]";
List<City> cityList = JsonUtils.getObjList(listStr, (v) => City.fromJson(v));
return new Scaffold(
//https://www.jianshu.com/p/82842d07e8fe
appBar: new AppBar(title: new Text("测试JsonUtils的功能")),
body: ListView(
children: <Widget>[
new Text("测试GetItHelper的功能"),
new Text(title1),
new Text("将对象[值]转换为JSON字符串:" + JsonUtils.encodeObj(city)),
RaisedButton(
onPressed: () {
String objStr = "{\"name\":\"成都市\"}";
City hisCity = JsonUtils.getObject(objStr, (v) => City.fromJson(v));
setState(() {
title1 = "City对象:"+hisCity.name;
});
},
color: const Color(0xffff0000),
child: new Text('转换JSON字符串[源]到对象'),
),
new Divider(),
new Text(title2),
RaisedButton(
onPressed: () {
setState(() {
setState(() {
title1 = "City对象列表:"+cityList.length.toString();
});
});
},
color: const Color(0xffff0000),
child: new Text('转换JSON字符串列表[源]到对象列表'),
),
new Text("将对象[值]转换为JSON字符串:" + cityList.length.toString()),
RaisedButton(
onPressed: () {
String objStr = "{\"name\":\"成都市\"}";
JsonUtils.printJson(objStr);
},
color: const Color(0xffff0000),
child: new Text('单纯的Json格式输出打印'),
),
RaisedButton(
onPressed: () {
String objStr = "{\"name\":\"成都市\"}";
JsonUtils.printJsonEncode(objStr);
},
color: const Color(0xffff0000),
child: new Text('单纯的Json格式输出打印'),
),
],
));
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.