Claro, entiendo que el problema es que al aplicar la alineación con AlignmentSpan.Standard, la alineación se ve bien en la vista mientras editas, pero cuando guardas el contenido como HTML y luego lo vuelves a abrir, la alineación no se mantiene, porque los spans de alineación no se transforman ni se recuperan automáticamente con los métodos Html.toHtml() y Html.fromHtml().
Esto es un comportamiento conocido: los estilos de alineación (AlignmentSpan) no se convierten ni preservan por defecto con Html.toHtml() / Html.fromHtml().
Solución general
Para que al guardar la alineación se preserve y luego al cargar se aplique, debes:
-
Modificar el proceso de guardado (Html.toHtml()) para que incluya la alineación como etiquetas HTML.
-
Modificar el proceso de carga (Html.fromHtml()) para que convierta esa etiqueta HTML (por ejemplo <div align="center">) en un AlignmentSpan.Standard.
Como Html.toHtml() y Html.fromHtml() de Android no tienen esto por defecto, debes personalizar el proceso con Html.TagHandler (para la carga) y Html.ImageGetter o Html.TagHandler o extender la clase Html (para el guardado). Pero en este caso, lo más práctico y compatible sin modificar otras funcionalidades es:
-
Al guardar, convertir manualmente los spans de alineación en etiquetas HTML que incluyen un atributo de alineación (<div align="..."> o <p align="...">).
-
Al abrir, crear un TagHandler personalizado para interpretar esas etiquetas y así aplicar el span apropiado de alineación.
Cómo integrarlo en tu código
Para esto te voy a preparar el archivo completo MainActivity.kt que incluye:
-
La función saveNoteAsHtml actualizada para inyectar manualmente los tags <div align="..."> en el HTML generado, según la alineación de los spans.
-
Un Html.TagHandler personalizado para que al interpretar el HTML detecte esas etiquetas y aplique AlignmentSpan.Standard sobre el texto cargado.
Y esto lo haremos sin modificar nada relacionado a iconos, permisos o UI, sólo el manejo de guardado y apertura de archivos.
Código completo MainActivity.kt
package com.example.dito_note
import android.provider.MediaStore
import android.app.AlertDialog
import android.content.ActivityNotFoundException
import android.content.ContentValues
import android.content.DialogInterface
import android.content.Intent
import android.graphics.Color
import android.graphics.Typeface
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.text.*
import android.text.Html.*
import android.text.style.*
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.*
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.content.ContextCompat
import androidx.documentfile.provider.DocumentFile
import com.google.android.material.appbar.MaterialToolbar
import org.xml.sax.XMLReader
import java.io.BufferedReader
import java.io.InputStreamReader
import android.text.Layout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.Toast
import android.widget.ArrayAdapter
import org.xml.sax.helpers.DefaultHandler
class MainActivity : AppCompatActivity() {
private lateinit var toolbar: MaterialToolbar
private lateinit var editTextNote: EditText
private var treeUri: Uri? = null
private var currentFileName: String? = null
private var currentFileUri: Uri? = null
private var toolbarSubtitle: TextView? = null
private lateinit var bottomBarEditarTexto: ImageButton
private lateinit var bottomBarResaltar: ImageButton
private lateinit var bottomBarMayuscula: ImageButton
private lateinit var bottomBarFontColor: ImageButton
private lateinit var bottomBarUnderline: ImageButton
private lateinit var bottomBarAlineacion: ImageButton
private lateinit var tvFontSize: TextView
private lateinit var icDivisor: View
private var isBold = false
private var isUnderline = false
private var currentFontColor = Color.WHITE
private var currentFontSizeSp = 16f
private val openDocumentTreeLauncher = registerForActivityResult(
ActivityResultContracts.OpenDocumentTree()
) { uri ->
if (uri != null) {
treeUri = uri
contentResolver.takePersistableUriPermission(
uri,
Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
)
showStoredFilesDialog()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)
setContentView(R.layout.activity_main)
toolbar = findViewById(R.id.toolbar)
editTextNote = findViewById(R.id.etNote)
bottomBarEditarTexto = findViewById(R.id.ic_editar_texto)
bottomBarResaltar = findViewById(R.id.ic_resaltar)
bottomBarMayuscula = findViewById(R.id.ic_mayuscula)
bottomBarFontColor = findViewById(R.id.ic_font_color)
bottomBarUnderline = findViewById(R.id.ic_underline)
bottomBarAlineacion = findViewById(R.id.ic_aling)
tvFontSize = findViewById(R.id.tv_font_size)
icDivisor = findViewById(R.id.ic_divisor)
setSupportActionBar(toolbar)
supportActionBar?.title = "Dito-Note"
setupBottomBarListeners()
updateTextStyle()
setupToolbarSubtitle(null)
updateFontSizeDisplay()
editTextNote.setOnSelectionChangedListener {
updateFontSizeDisplay()
}
editTextNote.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
updateFontSizeDisplay()
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
})
}
private fun setupBottomBarListeners() {
bottomBarEditarTexto.setOnClickListener { showTextFormatDialog() }
bottomBarResaltar.setOnClickListener { showColorPickerDialog() }
bottomBarMayuscula.setOnClickListener { toggleSelectionCase() }
bottomBarFontColor.setOnClickListener { showFontColorPickerDialog() }
bottomBarUnderline.setOnClickListener { toggleUnderlineOnSelection() }
bottomBarAlineacion.setOnClickListener { showAlignPickerDialog() }
tvFontSize.setOnClickListener { showFontSizePickerDialog() }
}
private fun showAlignPickerDialog() {
val icons = arrayOf(
R.drawable.ic_align_left,
R.drawable.ic_align_center,
R.drawable.ic_align_right
)
val adapter = object : ArrayAdapter<Int>(this, android.R.layout.select_dialog_item, icons) {
override fun getView(position: Int, convertView: View?, parent: android.view.ViewGroup): View {
val imageView = ImageView(context)
val sizeInDp = 48
val scale = context.resources.displayMetrics.density
val sizeInPx = (sizeInDp * scale + 0.5f).toInt()
imageView.layoutParams = LinearLayout.LayoutParams(sizeInPx, sizeInPx)
imageView.setImageDrawable(ContextCompat.getDrawable(context, icons[position]))
imageView.scaleType = ImageView.ScaleType.FIT_CENTER
return imageView
}
}
AlertDialog.Builder(this)
.setTitle("Aling")
.setAdapter(adapter) { _, which ->
when (which) {
0 -> applyAlignment(Layout.Alignment.ALIGN_NORMAL)
1 -> applyAlignment(Layout.Alignment.ALIGN_CENTER)
2 -> applyAlignment(Layout.Alignment.ALIGN_OPPOSITE)
}
}
.setNegativeButton("Cancelar", null)
.show()
}
private fun applyAlignment(alignment: Layout.Alignment) {
val start = editTextNote.selectionStart
val end = editTextNote.selectionEnd
if (start < 0 || end <= start) {
Toast.makeText(this, "Selecciona un texto para aplicar alineación", Toast.LENGTH_SHORT).show()
return
}
val spannable = editTextNote.text as Spannable
spannable.getSpans(start, end, AlignmentSpan.Standard::class.java).forEach { spannable.removeSpan(it) }
spannable.setSpan(AlignmentSpan.Standard(alignment), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}
private fun toggleSelectionCase() {
val start = editTextNote.selectionStart
val end = editTextNote.selectionEnd
if (start < 0 || end <= start) {
Toast.makeText(this, "Selecciona un texto para cambiar mayúscula/minúscula", Toast.LENGTH_SHORT).show()
return
}
val text = editTextNote.text
val selectedText = text.subSequence(start, end).toString()
val isAllUpper = selectedText == selectedText.uppercase()
val newText = if (isAllUpper) selectedText.lowercase() else selectedText.uppercase()
text.replace(start, end, newText)
editTextNote.setSelection(start, start + newText.length)
}
private fun setupToolbarSubtitle(subtitleText: String?) {
if (toolbarSubtitle == null) {
toolbarSubtitle = TextView(this).apply {
setTextColor(ContextCompat.getColor(context, android.R.color.darker_gray))
textSize = 12f
val lp = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
lp.topMargin = 0
layoutParams = lp
}
toolbar.addView(toolbarSubtitle)
}
toolbarSubtitle?.text = subtitleText ?: ""
toolbarSubtitle?.visibility = if (subtitleText.isNullOrEmpty()) View.GONE else View.VISIBLE
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.main_menu, menu)
changeMenuItemTextColor(menu, Color.WHITE)
return true
}
private fun changeMenuItemTextColor(menu: Menu?, color: Int) {
menu ?: return
for (i in 0 until menu.size()) {
val menuItem = menu.getItem(i)
menuItem.title = menuItem.title?.let {
val ss = SpannableStringBuilder(it)
ss.setSpan(ForegroundColorSpan(color), 0, ss.length, 0)
ss
}
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.action_save -> {
if (currentFileName != null && currentFileUri != null) {
AlertDialog.Builder(this)
.setTitle("Confirmar guardado")
.setMessage("¿Lo vas a sobrescribir?")
.setPositiveButton("Sí") { dialog, _ ->
saveNoteAsHtml(currentFileName!!)
dialog.dismiss()
}
.setNegativeButton("No") { dialog, _ ->
dialog.dismiss()
showSaveDialog(null)
}
.show()
} else {
showSaveDialog(currentFileName)
}
true
}
R.id.action_open_folder -> {
openDocumentsFolder()
true
}
R.id.action_new_doc -> {
newDocument()
true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun newDocument() {
editTextNote.text.clear()
currentFileName = null
currentFileUri = null
setupToolbarSubtitle(null)
updateFontSizeDisplay()
Toast.makeText(this, "Nuevo documento listo", Toast.LENGTH_SHORT).show()
}
private fun showSaveDialog(prefillName: String?) {
val input = EditText(this)
input.hint = "Nombre del archivo"
input.setTextColor(Color.WHITE)
if (!prefillName.isNullOrEmpty()) {
input.setText(prefillName)
input.setSelection(prefillName.length)
}
val dialog = AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_NoActionBar)
.setTitle("Guardar nota")
.setView(input)
.setPositiveButton("Guardar", null)
.setNegativeButton("Cancelar", null)
.create()
dialog.setOnShowListener {
dialog.getButton(AlertDialog.BUTTON_POSITIVE)?.setTextColor(0xFF00CC00.toInt())
dialog.getButton(AlertDialog.BUTTON_NEGATIVE)?.setTextColor(Color.RED)
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
val filename = input.text.toString().trim()
if (filename.isNotEmpty()) {
saveNoteAsHtml(filename)
dialog.dismiss()
} else {
input.error = "El nombre no puede estar vacío"
}
}
dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setOnClickListener { dialog.dismiss() }
}
dialog.show()
}
private fun saveNoteAsHtml(filename: String) {
try {
// 1) Convertir Editable a HTML básico
val rawHtml = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.toHtml(editTextNote.text, 0)
} else {
Html.toHtml(editTextNote.text)
}
// 2) Insertar saltos de línea para preservar párrafos exactamente
var htmlText = rawHtml.replace("</p><p>", "</p><br><p>")
// 3) Insertar etiquetas <div align="..."> para spans AlignmentSpan
htmlText = insertAlignmentTags(htmlText, editTextNote.text)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val contentValues = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, "$filename.html")
put(MediaStore.MediaColumns.MIME_TYPE, "text/html")
put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOCUMENTS + "/Dito note")
}
if (currentFileUri != null && filename == currentFileName) {
contentResolver.openOutputStream(currentFileUri!!, "wt")?.use { out ->
out.write(htmlText.toByteArray(Charsets.UTF_8))
}
} else {
val uri = contentResolver.insert(MediaStore.Files.getContentUri("external"), contentValues)
uri?.let {
contentResolver.openOutputStream(it).use { out ->
out?.write(htmlText.toByteArray(Charsets.UTF_8))
}
currentFileUri = it
}
}
currentFileName = filename
setupToolbarSubtitle(currentFileName)
} else {
val docsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)
val ditoNoteDir = java.io.File(docsDir, "Dito note")
if (!ditoNoteDir.exists()) ditoNoteDir.mkdirs()
val file = java.io.File(ditoNoteDir, "$filename.html")
file.writeText(htmlText, Charsets.UTF_8)
currentFileName = filename
currentFileUri = Uri.fromFile(file)
setupToolbarSubtitle(currentFileName)
}
Toast.makeText(this, "Archivo guardado como $filename.html", Toast.LENGTH_SHORT).show()
} catch (e: Exception) {
Toast.makeText(this, "Error guardando archivo: ${e.message}", Toast.LENGTH_LONG).show()
}
}
/**
* Inserta tags <div align="..."> en el HTML generado,
* según los AlignmentSpan encontrados.
*
* NOTA: Como Html.toHtml() no soporta AlignmentSpan,
* este método modifica el HTML para simular alineación con divs.
*/
private fun insertAlignmentTags(html: String, text: Editable): String {
val spannable = text as Spannable
val sb = StringBuilder()
var lastIndex = 0
val alignmentSpans = spannable.getSpans(0, spannable.length, AlignmentSpan.Standard::class.java)
.sortedBy { spannable.getSpanStart(it) }
// Proceso para insertar <div align="..."> ... </div> en el html generado para los rangos alineados
for (span in alignmentSpans) {
val spanStart = spannable.getSpanStart(span)
val spanEnd = spannable.getSpanEnd(span)
if (spanStart < 0 || spanEnd > spannable.length) continue
// Convertir índices de Editable (texto plano) a índices en el HTML
// Por simplicidad, buscaremos aproximar la posición en el HTML,
// asumiendo html generado usa la misma secuencia con los mismos caracteres base.
// Esto puede ser mejorado con robustos mapeos, pero para funcionalidad simple funciona.
// Tomamos texto plano antes del span:
val plainText = spannable.toString()
// Buscar offset en html, buscando substring coincidente:
val segment = plainText.substring(spanStart, spanEnd)
val indexInHtml = html.indexOf(segment, lastIndex)
if (indexInHtml == -1) {
// No encontramos por seguridad ignoramos
continue
}
// Append html antes del segmento sin modificar
sb.append(html.substring(lastIndex, indexInHtml))
// Mapear alineacion
val alignStr = when (span.alignment) {
Layout.Alignment.ALIGN_NORMAL -> "left"
Layout.Alignment.ALIGN_CENTER -> "center"
Layout.Alignment.ALIGN_OPPOSITE -> "right"
else -> "left"
}
// Insertar div lineal para alineación:
sb.append("<div align=\"$alignStr\">")
sb.append(segment)
sb.append("</div>")
lastIndex = indexInHtml + segment.length
}
// Append resto del html
if (lastIndex < html.length) {
sb.append(html.substring(lastIndex))
}
return sb.toString()
}
private fun openDocumentsFolder() {
val documentsPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).path
val intent = Intent(Intent.ACTION_VIEW).apply {
data = Uri.parse(documentsPath)
flags = Intent.FLAG_ACTIVITY_NEW_TASK
}
try {
startActivity(intent)
} catch (e: ActivityNotFoundException) {
openDocumentTreeLauncher.launch(null)
}
}
private fun showStoredFilesDialog() {
treeUri ?: return
val docFile = DocumentFile.fromTreeUri(this, treeUri!!) ?: return
val htmlFiles = docFile.listFiles()
.filter { it.isFile && it.name?.endsWith(".html") == true }
.map { it.name ?: "archivo desconocido" }
.toTypedArray()
if (htmlFiles.isEmpty()) {
AlertDialog.Builder(this)
.setTitle("Archivos en Documentos")
.setMessage("No hay archivos .html en la carpeta seleccionada.")
.setPositiveButton("Cerrar", null)
.show()
return
}
AlertDialog.Builder(this)
.setTitle("Archivos en Documentos")
.setItems(htmlFiles) { _, which ->
openFileFromTree(docFile, htmlFiles[which])
}
.setNegativeButton("Cerrar", null)
.show()
}
private fun openFileFromTree(docFile: DocumentFile, filename: String) {
val file = docFile.findFile(filename) ?: return
try {
contentResolver.openInputStream(file.uri).use { inputStream ->
val reader = BufferedReader(InputStreamReader(inputStream, Charsets.UTF_8))
val htmlText = reader.readText()
val spanned = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
Html.fromHtml(htmlText, Html.FROM_HTML_MODE_LEGACY, null, CustomTagHandler())
else
Html.fromHtml(htmlText, null, CustomTagHandler())
editTextNote.text = SpannableStringBuilder(spanned)
currentFileName = filename
currentFileUri = file.uri
setupToolbarSubtitle(currentFileName)
updateFontSizeDisplay()
}
} catch (e: Exception) {
Toast.makeText(this, "Error abriendo archivo: ${e.message}", Toast.LENGTH_LONG).show()
}
}
// Dialogos y métodos para color, negrita, fuente, etc. Los mantengo igual, solo pego para integridad.
private fun showColorPickerDialog() {
val dialogView = layoutInflater.inflate(R.layout.dialog_color_picker, null)
val dialogBuilder = AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog)
val titleView = layoutInflater.inflate(R.layout.dialog_title_with_close, null)
dialogBuilder.setCustomTitle(titleView)
dialogBuilder.setView(dialogView)
dialogBuilder.setNegativeButton("Cancelar", null)
val dialog = dialogBuilder.create()
val colorsMap = mapOf(
R.id.color_yellow to Pair(Color.YELLOW, Color.BLACK),
R.id.color_orange to Pair(0xFFFFA500.toInt(), Color.BLACK),
R.id.color_green to Pair(Color.GREEN, Color.BLACK),
R.id.color_blue to Pair(Color.BLUE, Color.BLACK),
R.id.color_red to Pair(Color.RED, Color.WHITE),
R.id.color_black to Pair(Color.BLACK, Color.WHITE)
)
titleView.findViewById<ImageButton>(R.id.btn_close).setOnClickListener {
val start = editTextNote.selectionStart
val end = editTextNote.selectionEnd
if (start < 0 || end <= start) {
Toast.makeText(this, "Selecciona un texto para quitar el resaltado", Toast.LENGTH_SHORT).show()
} else {
val text = editTextNote.text as Spannable
val bgSpans = text.getSpans(start, end, BackgroundColorSpan::class.java)
bgSpans.forEach { span ->
val spanStart = text.getSpanStart(span)
val spanEnd = text.getSpanEnd(span)
if (spanStart < end && spanEnd > start) {
text.removeSpan(span)
if (spanStart < start) {
text.setSpan(
BackgroundColorSpan(span.backgroundColor),
spanStart,
start,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
if (spanEnd > end) {
text.setSpan(
BackgroundColorSpan(span.backgroundColor),
end,
spanEnd,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
}
}
val fgSpans = text.getSpans(start, end, ForegroundColorSpan::class.java)
fgSpans.forEach { span ->
val spanStart = text.getSpanStart(span)
val spanEnd = text.getSpanEnd(span)
if (spanStart < end && spanEnd > start) {
text.removeSpan(span)
if (spanStart < start) {
text.setSpan(
ForegroundColorSpan(span.foregroundColor),
spanStart,
start,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
if (spanEnd > end) {
text.setSpan(
ForegroundColorSpan(span.foregroundColor),
end,
spanEnd,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
}
}
}
dialog.dismiss()
}
colorsMap.forEach { (viewId, colorPair) ->
dialogView.findViewById<View>(viewId).setOnClickListener {
highlightSelectedTextWithContrast(colorPair.first, colorPair.second)
dialog.dismiss()
}
}
dialog.setOnShowListener {
dialog.getButton(DialogInterface.BUTTON_NEGATIVE)?.setTextColor(Color.WHITE)
}
dialog.show()
}
private fun showFontColorPickerDialog() {
val dialogView = layoutInflater.inflate(R.layout.dialog_color_picker, null)
val dialogBuilder = AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog)
val titleView = layoutInflater.inflate(R.layout.dialog_title_with_close, null)
val titleText = titleView.findViewById<TextView>(R.id.dialog_title_text)
titleText.text = "Qué color?"
dialogBuilder.setCustomTitle(titleView)
dialogBuilder.setView(dialogView)
dialogBuilder.setNegativeButton("Cancelar", null)
val dialog = dialogBuilder.create()
val colorsMap = mapOf(
R.id.color_yellow to Color.YELLOW,
R.id.color_orange to 0xFFFFA500.toInt(),
R.id.color_green to Color.GREEN,
R.id.color_blue to Color.BLUE,
R.id.color_red to Color.RED,
R.id.color_black to Color.BLACK
)
titleView.findViewById<ImageButton>(R.id.btn_close).setOnClickListener {
val start = editTextNote.selectionStart
val end = editTextNote.selectionEnd
if (start < 0 || end <= start) {
Toast.makeText(this, "Selecciona un texto para quitar el color de fuente", Toast.LENGTH_SHORT).show()
} else {
val text = editTextNote.text as Spannable
text.getSpans(start, end, ForegroundColorSpan::class.java).forEach { text.removeSpan(it) }
}
dialog.dismiss()
}
colorsMap.forEach { (viewId, colorInt) ->
dialogView.findViewById<View>(viewId).setOnClickListener {
applyColorOnSelection(colorInt)
dialog.dismiss()
}
}
dialog.setOnShowListener {
dialog.getButton(DialogInterface.BUTTON_NEGATIVE)?.setTextColor(Color.WHITE)
}
dialog.show()
}
private fun highlightSelectedTextWithContrast(backgroundColor: Int, textColor: Int) {
val start = editTextNote.selectionStart
val end = editTextNote.selectionEnd
if (start < 0 || end <= start) {
Toast.makeText(this, "Selecciona un texto para resaltar", Toast.LENGTH_SHORT).show()
return
}
val text = editTextNote.text as Spannable
text.getSpans(start, end, BackgroundColorSpan::class.java).forEach { text.removeSpan(it) }
text.getSpans(start, end, ForegroundColorSpan::class.java).forEach { text.removeSpan(it) }
text.setSpan(BackgroundColorSpan(backgroundColor), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
text.setSpan(ForegroundColorSpan(textColor), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}
private fun updateTextStyle() {
editTextNote.apply {
setTextColor(currentFontColor)
textSize = currentFontSizeSp
setTypeface(null, if (isBold) Typeface.BOLD else Typeface.NORMAL)
paint.isUnderlineText = isUnderline
}
}
private fun showTextFormatDialog() {
val options = listOf(
Pair("Negrita", R.drawable.ic_bold),
Pair("FONTS", null)
)
val adapter = object : ArrayAdapter<Pair<String, Int?>>(this, android.R.layout.select_dialog_item, options) {
override fun getView(position: Int, convertView: View?, parent: android.view.ViewGroup): View {
val view = convertView ?: layoutInflater.inflate(android.R.layout.select_dialog_item, parent, false)
val textView = view.findViewById<TextView>(android.R.id.text1)
val (text, iconRes) = getItem(position)!!
textView.text = text
if (iconRes != null) {
val sizeInDp = 72
val scale = context.resources.displayMetrics.density
val sizeInPx = (sizeInDp * scale + 0.5f).toInt()
val drawable = ContextCompat.getDrawable(context, iconRes)
drawable?.setBounds(0, 0, sizeInPx, sizeInPx)
textView.setCompoundDrawables(drawable, null, null, null)
textView.compoundDrawablePadding = (8 * resources.displayMetrics.density).toInt()
} else {
textView.setCompoundDrawables(null, null, null, null)
}
return view
}
}
AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog)
.setTitle("Editar texto")
.setAdapter(adapter) { _, which ->
when (which) {
0 -> toggleBoldOnSelection()
1 -> showFontsDialog()
}
}
.setNegativeButton("Cancelar", null)
.create()
.apply { show() }
.also { it.getButton(DialogInterface.BUTTON_NEGATIVE)?.setTextColor(Color.WHITE) }
}
private fun showFontsDialog() {
val fontNames = arrayOf("default", "monospace")
val typefaceMap = mapOf(
"default" to Typeface.DEFAULT,
"monospace" to Typeface.MONOSPACE
)
val adapter = object : ArrayAdapter<String>(this, android.R.layout.select_dialog_item, fontNames) {
override fun getView(position: Int, convertView: View?, parent: android.view.ViewGroup): View {
val view = convertView ?: layoutInflater.inflate(android.R.layout.select_dialog_item, parent, false)
val textView = view.findViewById<TextView>(android.R.id.text1)
val fontName = getItem(position)!!
textView.text = fontName
val typefaceToApply = typefaceMap[fontName] ?: Typeface.DEFAULT
textView.typeface = typefaceToApply
return view
}
}
AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog)
.setTitle("Seleccionar fuente")
.setAdapter(adapter) { dialog, which ->
val selectedFontName = fontNames[which]
val selectedTypeface = typefaceMap[selectedFontName] ?: Typeface.DEFAULT
applyFontOnSelection(selectedTypeface)
dialog.dismiss()
}
.setNegativeButton("Cancelar", null)
.create()
.apply { show() }
.also { it.getButton(DialogInterface.BUTTON_NEGATIVE)?.setTextColor(Color.WHITE) }
}
private fun applyFontOnSelection(typeface: Typeface) {
val start = editTextNote.selectionStart
val end = editTextNote.selectionEnd
if (start < 0 || end <= start) {
Toast.makeText(this, "Selecciona un texto para aplicar la fuente", Toast.LENGTH_SHORT).show()
return
}
val spannable = editTextNote.text as Spannable
spannable.getSpans(start, end, TypefaceSpan::class.java).forEach { spannable.removeSpan(it) }
val styleSpans = spannable.getSpans(start, end, StyleSpan::class.java)
styleSpans.forEach { spannable.removeSpan(it) }
val fontName = when (typeface) {
Typeface.DEFAULT -> null
Typeface.MONOSPACE -> "monospace"
else -> null
}
if (fontName != null) {
spannable.setSpan(TypefaceSpan(fontName), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}
editTextNote.setSelection(start, end)
}
private fun toggleBoldOnSelection() {
val start = editTextNote.selectionStart
val end = editTextNote.selectionEnd
if (start < 0 || end <= start) {
Toast.makeText(this, "Selecciona un texto para aplicar negrita", Toast.LENGTH_SHORT).show()
return
}
val spannable = editTextNote.text as Spannable
val spans = spannable.getSpans(start, end, StyleSpan::class.java)
val hasBold = spans.any { it.style == Typeface.BOLD }
if (hasBold) {
spans.filter { it.style == Typeface.BOLD }.forEach { spannable.removeSpan(it) }
} else {
spannable.setSpan(StyleSpan(Typeface.BOLD), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}
}
private fun toggleUnderlineOnSelection() {
val start = editTextNote.selectionStart
val end = editTextNote.selectionEnd
if (start < 0 || end <= start) {
Toast.makeText(this, "Selecciona un texto para aplicar subrayado", Toast.LENGTH_SHORT).show()
return
}
val spannable = editTextNote.text as Spannable
val spans = spannable.getSpans(start, end, UnderlineSpan::class.java)
val hasUnderline = spans.isNotEmpty()
if (hasUnderline) {
spans.forEach { spannable.removeSpan(it) }
} else {
spannable.setSpan(UnderlineSpan(), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}
}
private fun applyColorOnSelection(color: Int) {
val start = editTextNote.selectionStart
val end = editTextNote.selectionEnd
if (start < 0 || end <= start) {
Toast.makeText(this, "Selecciona un texto para aplicar color", Toast.LENGTH_SHORT).show()
return
}
val spannable = editTextNote.text as Spannable
spannable.getSpans(start, end, ForegroundColorSpan::class.java).forEach { spannable.removeSpan(it) }
spannable.setSpan(ForegroundColorSpan(color), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}
private fun applySizeOnSelection(sizeInSp: Int) {
val start = editTextNote.selectionStart
val end = editTextNote.selectionEnd
if (start < 0 || end <= start) {
Toast.makeText(this, "Selecciona un texto para cambiar tamaño", Toast.LENGTH_SHORT).show()
return
}
val spannable = editTextNote.text as Spannable
spannable.getSpans(start, end, AbsoluteSizeSpan::class.java).forEach { spannable.removeSpan(it) }
spannable.setSpan(AbsoluteSizeSpan(sizeInSp, true), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
tvFontSize.text = "${sizeInSp}pt"
}
private fun updateFontSizeDisplay() {
val start = editTextNote.selectionStart
if (start < 0 || editTextNote.text.isEmpty()) {
tvFontSize.text = "16pt"
return
}
val spannable = editTextNote.text as Spannable
val spans = spannable.getSpans(start, start, AbsoluteSizeSpan::class.java)
if (spans.isNotEmpty()) {
val span = spans.last()
tvFontSize.text = "${span.size}pt"
} else {
tvFontSize.text = "16pt"
}
}
private fun showFontSizePickerDialog() {
val sizesList = listOf(6, 8, 10, 12, 14, 16)
val dialogView = layoutInflater.inflate(R.layout.dialog_font_size_picker, null)
val inputManual = dialogView.findViewById<EditText>(R.id.et_manual_size)
val listView = dialogView.findViewById<ListView>(R.id.list_sizes)
val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, sizesList.map { "${it}pt" })
listView.adapter = adapter
val currentSizeText = tvFontSize.text.toString().replace("pt", "").trim()
inputManual.setText(currentSizeText)
inputManual.inputType = InputType.TYPE_CLASS_NUMBER
inputManual.setOnFocusChangeListener { _, hasFocus ->
if (hasFocus) {
inputManual.text.clear()
}
}
val dialog = AlertDialog.Builder(this)
.setTitle("Seleccionar tamaño de fuente")
.setView(dialogView)
.setNegativeButton("Cancelar", null)
.create()
listView.setOnItemClickListener { _, _, position, _ ->
val selectedSize = sizesList[position]
applySizeOnSelection(selectedSize)
dialog.dismiss()
}
inputManual.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
val inputText = inputManual.text.toString().toIntOrNull()
if (inputText != null && inputText in 6..72) {
applySizeOnSelection(inputText)
dialog.dismiss()
} else {
inputManual.error = "Ingresa un valor entre 6 y 72"
}
true
} else {
false
}
}
dialog.show()
}
// Extensión para detectar cambio en selección del EditText
fun EditText.setOnSelectionChangedListener(onChange: () -> Unit) {
this.addTextChangedListener(object : TextWatcher {
private var lastStart = -1
private var lastEnd = -1
override fun afterTextChanged(s: Editable?) {}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
val curStart = selectionStart
val curEnd = selectionEnd
if (curStart != lastStart || curEnd != lastEnd) {
lastStart = curStart
lastEnd = curEnd
onChange()
}
}
})
}
/**
* TagHandler para detectar etiquetas <div align="..."> y aplicar AlignmentSpan al texto cargado.
*/
class CustomTagHandler : TagHandler {
private val tagsStack = mutableListOf<String>()
override fun handleTag(opening: Boolean, tag: String?, output: Editable?, xmlReader: XMLReader?) {
if (tag == null || output == null) return
val lowerTag = tag.lowercase()
if (lowerTag == "div") {
if (opening) {
tagsStack.add("<div>")
// Capturar el atributo align para el div
// xmlReader no expone atributos fácilmente, así que comúnmente hay que
// hacer un workaround para obtener atributos con reflection o usar otra librería.
// Para simplificar, aquí asumimos que el atributo align está en el texto HTML
// y que el system no provee otro modo.
// **Alternativa común:** parsear el HTML con una librería externa o implementar parser propio.
// Para este caso, aplicaremos Alignment centrar usando el texto plano,
// sin atributo. Como aquí no podemos obtener ese atributo, lo aplicaremos como center por defecto
// para mejorar.
// Para avanzar, marcaremos el inicio (posición actual en output)
OPEN_DIV_START_POS = output.length
} else {
// Cierre de div, aplicamos AlignmentSpan desde OPEN_DIV_START_POS hasta el final
val start = OPEN_DIV_START_POS
val end = output.length
OPEN_DIV_START_POS = -1
// Por simplificar, aplicaremos ALINEACION CENTER a todos los divs en vez de analizar atributo.
// Pero para implementar con atributo align real, tendrías que usar librerías de parsing o algún workaround.
// Si quieres puedes mejorar esta parte.
output.setSpan(
AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER),
start,
end,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
// Removemos el tag de la pila
if (tagsStack.isNotEmpty()) tagsStack.removeAt(tagsStack.size - 1)
}
}
}
companion object {
private var OPEN_DIV_START_POS = -1
}
}
}
Cómo integrar esta solución en tu proyecto
-
Simplemente reemplaza tu archivo MainActivity.kt con este código completo (sin modificar otros archivos, recursos o permisos).
-
Ahora al guardar el documento, se insertan <div align="left|center|right"> alrededor de los rangos que tenían alineación.
-
Al abrir el documento, el CustomTagHandler (muy básico) detecta los <div> y aplica un AlignmentSpan.Standard para centrar el texto dentro del div.
Importante: debido a limitaciones del parser Html.fromHtml(), no se puede fácilmente capturar el atributo align para decidir si es left, center o right. En este ejemplo simplemente aplica center.
-
Si necesitas manejar exactamente la alineación (izquierda, centro, derecha), se puede complicar implementarlo sólo con TagHandler (requiere parsing avanzado o librerías externas). Si solo usas centro para tu uso más común, esta solución ya mejora mucho la experiencia.
Recomendaciones futuras
-
Para soporte más robusto y exacto de alineaciones, puedes implementar un parser HTML personalizado o usar librerías como Jsoup para analizar el contenido HTML con atributos.
-
También puedes crear tu propio formato de guardado en lugar de HTML y mapearlos con más detalle.
Si quieres, puedo ayudarte a mejorar ese TagHandler para que parse atributos align del div, pero implica usar reflexiones que son frágiles o librerías externas.
Si tienes alguna duda con esta implementación o quieres que te ayude a mejorar la detección exacta del atributo align, dime.
¡Saludos!