Te mando los codigos completos, los revisas y comparas solamente la funcion de aling de Note25....para que funcione en Dito-Note. MUY INPORTANTE RECORDAR, sin tocar ni modificar nada que afecte iconos, textos, permisos u otras funcionalidades.mandame el archivo completo con absolutamente todas las funciones sin abreviar. Dame el codigo COMPLETO Y LIMPIO, para solamente copiar y pegar. package com.example.dito_note
import android.provider.MediaStore
import android.app.AlertDialog
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.Gravity
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 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
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: ImageButton
private var isBold = false
private var isUnderline = false
private var currentFontColor = Color.WHITE
private var currentFontSizeSp = 16f
private var currentTextAlignment: Int = View.TEXT_ALIGNMENT_TEXT_START
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() }
icDivisor.setOnClickListener {
showDivisorMenu()
}
}
private fun showDivisorMenu() {
val paint = editTextNote.paint
val editTextWidth = editTextNote.width - editTextNote.paddingLeft - editTextNote.paddingRight
if (editTextWidth <= 0) {
Toast.makeText(this, "EditText no ha sido layoutedo aún", Toast.LENGTH_SHORT).show()
return
}
val equalCharWidth = paint.measureText("=")
val dashCharWidth = paint.measureText("-")
val equalCharCount = if (equalCharWidth != 0f) (editTextWidth / equalCharWidth).toInt().coerceAtLeast(1) else 20
val dashCharCount = if (dashCharWidth != 0f) (editTextWidth / dashCharWidth).toInt().coerceAtLeast(1) else 20
val halfDashCharCount = (dashCharCount / 2).coerceAtLeast(1)
val options = arrayOf(
"=================== (Ancho completo)",
"------------------- (Ancho completo)",
"---------- (Mitad ancho)"
)
AlertDialog.Builder(this)
.setTitle("Divisor")
.setItems(options) { dialog, which ->
val cursorPos = editTextNote.selectionStart.coerceAtLeast(0)
val divisorText = when (which) {
0 -> "=".repeat(equalCharCount) + "\n"
1 -> "-".repeat(dashCharCount) + "\n"
2 -> "-".repeat(halfDashCharCount) + "\n"
else -> null
}
divisorText?.let {
editTextNote.text.insert(cursorPos, it)
editTextNote.setSelection(cursorPos + it.length)
}
dialog.dismiss()
}
.show()
}
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) {
when (alignment) {
Layout.Alignment.ALIGN_NORMAL -> {
editTextNote.textAlignment = View.TEXT_ALIGNMENT_TEXT_START
editTextNote.gravity = Gravity.START or Gravity.TOP
currentTextAlignment = View.TEXT_ALIGNMENT_TEXT_START
}
Layout.Alignment.ALIGN_CENTER -> {
editTextNote.textAlignment = View.TEXT_ALIGNMENT_CENTER
editTextNote.gravity = Gravity.CENTER_HORIZONTAL or Gravity.TOP
currentTextAlignment = View.TEXT_ALIGNMENT_CENTER
}
Layout.Alignment.ALIGN_OPPOSITE -> {
editTextNote.textAlignment = View.TEXT_ALIGNMENT_TEXT_END
editTextNote.gravity = Gravity.END or Gravity.TOP
currentTextAlignment = View.TEXT_ALIGNMENT_TEXT_END
}
else -> {
editTextNote.textAlignment = View.TEXT_ALIGNMENT_TEXT_START
editTextNote.gravity = Gravity.START or Gravity.TOP
currentTextAlignment = View.TEXT_ALIGNMENT_TEXT_START
}
}
}
// Resto de funciones para edición de texto, formatos, guardar, abrir, etc.
// Puedes copiar directamente las funciones de tu código original sin modificaciones.
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 {
val rawHtml = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.toHtml(editTextNote.text, 0)
} else {
Html.toHtml(editTextNote.text)
}
val htmlText = rawHtml.replace("</p><p>", "</p><br><p>")
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()
}
}
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: Exception) {
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)
else
Html.fromHtml(htmlText)
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()
}
}
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()
}
}
})
} --------------------------------------------package com.example.note25
import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.OpenableColumns
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import com.example.note25.ui.theme.Note25Theme
import java.io.BufferedReader
import java.io.File
import java.io.FileOutputStream
import java.io.InputStreamReader
@OptIn(ExperimentalMaterial3Api::class)
class MainActivity : ComponentActivity() {
private lateinit var prefs: android.content.SharedPreferences
private val _noteText = mutableStateOf("")
private val _textAlign = mutableStateOf(TextAlign.Start)
private val _showSaveDialog = mutableStateOf(false)
private val _currentFileName = mutableStateOf("")
private var textToSave: String = ""
private var currentFileName: String = ""
private lateinit var requestPermissionLauncher: androidx.activity.result.ActivityResultLauncher<String>
private var pickedFolderUri: Uri? = null
// Lanzador para abrir archivo
private val openFileLauncher = registerForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
if (uri == null) {
Toast.makeText(this, "No se seleccionó archivo", Toast.LENGTH_SHORT).show()
return@registerForActivityResult
}
contentResolver.takePersistableUriPermission(
uri,
Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
)
loadFileContent(uri)
}
// Lanzador para abrir carpeta
private val openFolderLauncher = registerForActivityResult(ActivityResultContracts.OpenDocumentTree()) { uri ->
if (uri == null) {
Toast.makeText(this, "No se seleccionó carpeta", Toast.LENGTH_SHORT).show()
return@registerForActivityResult
}
contentResolver.takePersistableUriPermission(
uri,
Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
)
pickedFolderUri = uri
Toast.makeText(this, "Carpeta seleccionada", Toast.LENGTH_SHORT).show()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
prefs = getSharedPreferences("note25_prefs", Context.MODE_PRIVATE)
requestPermissionLauncher = registerForActivityResult(
ActivityResultContracts.RequestPermission()
) { isGranted ->
if (isGranted) {
saveFileToDocuments(currentFileName, textToSave)
} else {
Toast.makeText(this, "Permiso denegado, no se puede guardar", Toast.LENGTH_SHORT).show()
}
}
setContent {
Note25Theme {
Scaffold(
topBar = {
TopBar(
onSaveClicked = { _showSaveDialog.value = true },
onOpenFileClicked = { openFileLauncher.launch(arrayOf("text/plain")) },
onOpenFolderClicked = { openFolderLauncher.launch(null) }
)
},
bottomBar = {
BottomBar(
currentAlign = _textAlign.value,
onAlignChange = { newAlign ->
_textAlign.value = newAlign
saveAlignmentForFile(_currentFileName.value, newAlign)
}
)
},
) { paddingValues ->
NoteScreen(
modifier = Modifier
.padding(paddingValues)
.fillMaxSize(),
textAlign = _textAlign.value,
noteText = _noteText.value,
onNoteTextChange = { _noteText.value = it }
)
}
if (_showSaveDialog.value) {
SaveFileDialog(
initialText = _currentFileName.value,
onDismiss = { _showSaveDialog.value = false },
onSave = { fileName ->
if (fileName.isBlank()) {
Toast.makeText(this@MainActivity, "El nombre no puede estar vacío", Toast.LENGTH_SHORT).show()
return@SaveFileDialog
}
_currentFileName.value = fileName
textToSave = _noteText.value
currentFileName = fileName
_showSaveDialog.value = false
requestWritePermissionAndSave()
}
)
}
}
}
}
private fun saveAlignmentForFile(fileName: String, textAlign: TextAlign) {
if (fileName.isBlank()) return
val alignString = when (textAlign) {
TextAlign.Center -> "center"
TextAlign.End -> "end"
else -> "start"
}
prefs.edit().putString("align_$fileName", alignString).apply()
}
private fun getAlignmentForFile(fileName: String): TextAlign {
if (fileName.isBlank()) return TextAlign.Start
return when (prefs.getString("align_$fileName", "start")) {
"center" -> TextAlign.Center
"end" -> TextAlign.End
else -> TextAlign.Start
}
}
private fun loadFileContent(uri: Uri) {
try {
val inputStream = contentResolver.openInputStream(uri)
val reader = BufferedReader(InputStreamReader(inputStream))
val content = reader.readText()
reader.close()
inputStream?.close()
_noteText.value = content
val fileName = queryFileName(uri) ?: ""
_currentFileName.value = fileName
_textAlign.value = getAlignmentForFile(fileName)
Toast.makeText(this, "Archivo cargado", Toast.LENGTH_SHORT).show()
} catch (e: Exception) {
Toast.makeText(this, "Error abriendo archivo: ${e.message}", Toast.LENGTH_LONG).show()
}
}
private fun queryFileName(uri: Uri): String? {
val cursor = contentResolver.query(uri, null, null, null, null)
cursor?.use {
if (it.moveToFirst()) {
val index = it.getColumnIndex(OpenableColumns.DISPLAY_NAME)
if (index != -1) {
return it.getString(index).removeSuffix(".txt")
}
}
}
return null
}
private fun requestWritePermissionAndSave() {
when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q -> {
// Android 10+ no necesita permiso para carpeta pública Documents
saveFileToDocuments(currentFileName, textToSave)
}
ContextCompat.checkSelfPermission(
this,
Manifest.permission.WRITE_EXTERNAL_STORAGE
) == PackageManager.PERMISSION_GRANTED -> {
// Permiso concedido
saveFileToDocuments(currentFileName, textToSave)
}
else -> {
// Solicitar permiso
requestPermissionLauncher.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE)
}
}
}
private fun saveFileToDocuments(fileName: String, text: String) {
try {
val docsFolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)
if (!docsFolder.exists()) docsFolder.mkdirs()
val file = File(docsFolder, "$fileName.txt")
FileOutputStream(file).use {
it.write(text.toByteArray())
}
Toast.makeText(this, "Guardado en: ${file.absolutePath}", Toast.LENGTH_LONG).show()
} catch (e: Exception) {
Toast.makeText(this, "Error guardando archivo: ${e.message}", Toast.LENGTH_LONG).show()
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TopBar(
onSaveClicked: () -> Unit,
onOpenFileClicked: () -> Unit,
onOpenFolderClicked: () -> Unit
) {
CenterAlignedTopAppBar(
title = { Text("Note25") },
actions = {
IconButton(onClick = onSaveClicked) {
Icon(Icons.Filled.Save, contentDescription = "Guardar")
}
IconButton(onClick = onOpenFileClicked) {
Icon(Icons.Filled.FolderOpen, contentDescription = "Abrir archivo")
}
IconButton(onClick = onOpenFolderClicked) {
Icon(Icons.Filled.Folder, contentDescription = "Abrir carpeta")
}
}
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun BottomBar(currentAlign: TextAlign, onAlignChange: (TextAlign) -> Unit) {
Surface(
tonalElevation = 3.dp,
shadowElevation = 3.dp,
modifier = Modifier
.fillMaxWidth()
.imePadding()
.navigationBarsPadding()
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 8.dp),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
IconButton(
onClick = { onAlignChange(TextAlign.Start) },
enabled = currentAlign != TextAlign.Start
) {
Icon(Icons.Filled.FormatAlignLeft, contentDescription = "Alinear a la izquierda")
}
Spacer(Modifier.width(24.dp))
IconButton(
onClick = { onAlignChange(TextAlign.Center) },
enabled = currentAlign != TextAlign.Center
) {
Icon(Icons.Filled.FormatAlignCenter, contentDescription = "Alinear al centro")
}
Spacer(Modifier.width(24.dp))
IconButton(
onClick = { onAlignChange(TextAlign.End) },
enabled = currentAlign != TextAlign.End
) {
Icon(Icons.Filled.FormatAlignRight, contentDescription = "Alinear a la derecha")
}
}
}
}
@Composable
fun SaveFileDialog(initialText: String, onDismiss: () -> Unit, onSave: (String) -> Unit) {
var inputText by remember { mutableStateOf(initialText) }
AlertDialog(
onDismissRequest = onDismiss,
title = { Text("Guardar archivo") },
text = {
OutlinedTextField(
value = inputText,
onValueChange = { inputText = it },
label = { Text("Nombre del archivo") },
singleLine = true,
placeholder = { Text("Ingresa nombre sin extensión") }
)
},
confirmButton = {
TextButton(onClick = { onSave(inputText.trim()) }) {
Text("Guardar")
}
},
dismissButton = {
TextButton(onClick = onDismiss) {
Text("Cancelar")
}
}
)
}
@Composable
fun NoteScreen(
modifier: Modifier = Modifier,
textAlign: TextAlign,
noteText: String,
onNoteTextChange: (String) -> Unit
) {
Column(
modifier = modifier.padding(16.dp)
) {
OutlinedTextField(
value = noteText,
onValueChange = onNoteTextChange,
modifier = Modifier.fillMaxSize(),
placeholder = { Text("Escribe tu nota aquí...") },
textStyle = LocalTextStyle.current.copy(textAlign = textAlign),
maxLines = 15,
singleLine = false,
)
}
}