Com example android notepad что это
This article is a self-study note, welcome to reprint, but please indicate the source:
Through the previous 10 sections, most of the functions of Notepad have been realized, including adding photos, adding photos, adding recordings, adding drawings, and adding handwriting. In addition, you can find that there is one more option in the bottom menu. Realization again, used to expand the function of Notepad.
In this section, we will add database support for our notebook, so that you can save it in the database after adding a note, so that it can be viewed, modified, deleted, etc. next time.
First look at the renderings:
The three pictures demonstrate saving notes, viewing notes, and deleting notes respectively.
For a database, it is nothing more than the creation, deletion, modification, and investigation of the database.
In order to encapsulate the operation of the database, a separate class is written as follows:
Database operation
With the relevant operations of these databases, the following will start to implement the functions of saving notes, modifying notes, deleting notes, and querying notes.
Save note
When a note is edited, click the save button at the top to insert the note into the database. Of course, if there are pictures, recordings, etc. in the note, there is no picture, the recording itself is stored in the database, but Store its path in the database, and then read it from the database when you view it again, and take out the source file according to the saved path.
The idea of saving a note is to take out the content in the EditText, and extract the previous part from it as the title of the note, and at the same time save the time when the note is added.
The main code is:
Among them, the getTitle() function is to intercept the first 15 characters of the note body as the note's title; editModel indicates whether the note is currently added or modified. getTitle() is as follows:
The regular expression is mainly used here to match whether it is ordinary text or picture recording. If it is a picture recording, the picture recording text is obviously in the title. A technique is also used here, which is the last sentence of return, the purpose It is to uniformly replace the special characters such as carriage return in the title with spaces.
Browse (modify) notes
After saving the note, of course it must be retrieved from the database and displayed to the user in the original format. Imagine that after adding a note, return to the home page or re-enter the home page, you should see the list of currently saved notes, so a list (ListView) should be placed in the Activity of the home page to display the data retrieved from the database . When you click on an item in the list, you should open it to view the details of the note.
Because a part of the note has been intercepted as the title when saving the note, only the title and time are displayed on the note list on the homepage, and the detailed content is not obvious. Under the main code:
Among them, showNotesList() is used to obviously note the list, as follows:
The above only realizes the function of browsing the list of notes, then clicking on the list item will naturally view or modify the detailed content of the note, so add a click event to the list and read the corresponding note content from the database in its listener. And display as follows:
In this way, when a list item is clicked, a new activity will be opened to display the detailed content of the note. The new note activity is still used here. The advantage of this is that you can modify the note while viewing it. This is also the method used by most note-taking software, and it is also possible to pass some information to AddActivity via intent, where editModel is the edit mode, because here is to view or modify, so when you click save again, the original note will be updated That is, it is not to add a new note; noteId is to let AddActivity know which piece of data in the database should be read. Correspondingly, add code in AddActivity to fetch data and display it. The main code is as follows:
The regular expression is also used here, because the path needs to be identified. Through this method, this method is called every time AddActivity is opened, which can be used to add notes or modify notes.
Delete note
The implementation of deleting a note is still implemented in the home page Activity. When the list item is long-pressed, the operation selection pops up. There are two in total, one is for editing, the other is for deleting , The editing here is the same as clicking the list item to view the note function, mainly delete, when the delete is selected, the corresponding note entry will be deleted from the database, and the list will be refreshed. The main code is as follows:
Above, the functions of saving, modifying, and deleting notes have been realized. At this point, the functions of the notepad have been basically completed, and the rest is the follow-up improvement and optimization, as well as new functions.
Заключение
Our main content of this film is to use fragment argument to realize the data transfer between fragment and Activity, so as to complete the interactive process of diary list and creation of diary page.
On the basis of the previous, let's first add a click event to the list item of RecyclerView. Recall that we implemented the NoteListAdapter in the previous article, where the ViewHolder is associated with the list view, so we can achieve this by implementing a click event for the ViewHolder.
Modify the NoteListAdapter code:
Let's try the effect:
Next, we start the creation diary page when we click on the list. Starting the Activity in the fragment is similar to starting the activity from the activity. Here I renamed NotePageActivity to NoteItemActivity, NoteCreateFragment to NoteItemFragment, and fragment_note_create.xml to fragment_note_item.xml.
Replace the Toast statement above as follows:
Since our adapter is an independent java class, here we get the context through v.getContext(). To start a new Activity, in fact, it still calls the startActivity method of the associated Activity.
See if the program can start NoteItemActivity correctly as we have:
You can see but it can start our NoteItemActivity.
🐖: If our Adapter and ViewHolder are implemented as internal classes of the fragment, then you can directly call the getActivity() method to obtain 。
Everyone has also noticed that although the page jumped correctly, our creation diary page did not pass the content of the item we clicked on. Next, we will implement this content.
First we define the following variables in NoteListAdapter
Recall that Activity uses Intent to transfer data. Here we use it in the static class ViewHolder. We need to access non-static variables. Obviously this cannot be done. So here we modify the class qualifier of ViewHolder to public, and get the current NoteItem object in the onClick method.
Looking at the above code, it seems that there is nothing wrong with it, but the putExtra method does not have a corresponding method to transfer class objects for us to use, so here we need to use Gson to convert the NoteItem object into a json string for transfer.
This method returns the position of the data in the Adapter, consider using it when using the Adapter.
There is also a getLayoutPosition method, which returns the latest calculated position in the layout, which is consistent with the position seen by the user, and is considered for user input (such as a click event).
The difference between the two is:
getLayoutPosition and getAdapterPosition are usually the same. Only when the content in the Adapter changes and the Layout has not had time to draw, can it be different. This time is less than 16ms.
If notifyDataSetChanged() is called, because all items need to be redrawn, the RecyclerView does not know the adapterPosition before the drawing is completed, and it will return -1 (NO_POSITION) at this time. In most cases, getAdapterPosition is used. As long as you do not use notifyDataSetChanged() to refresh the data, you can always get the correct position value immediately.
Then we need to get the data, but here we need to get the data in NoteItemFragment. This is still somewhat different from the data passed by the Intent that we used to get the Activity.
Let's take a look at the solutions we can think of at a glance. Since we need to get the extra information of the intent in the fragment, we can get the Activity instance through getActivity(), and then get the extra information.
NoteItemFragment modified code is as follows:
Considering that NoteItemFragment may complete the functions of creating and editing diary at the same time, add the corresponding interpretation here. If we can or get the corresponding Extra information, then we are completing the corresponding assignment operation.
But using this method for data transfer will undoubtedly make our Fragment dependent on Activity, which is obviously not a good solution.
The basic idea of this implementation is to store the data in the argument bundle of the fragment, so that there is no need to specify the existence of extra in the intent of the managed activity, and the fragment itself can obtain the extra data it needs.
Modify NoteItemFragment.java and add the static method newInstance(Object extra), where extra is the extra information we need to pass.
Since we directly pass the class object of NoteItem here, we directly set the parameter type to Parcelable type. At the same time, we need to modify the code of NoteItem to extend Parcelable.
Modify the passed data in NoteListAdapter as follows:
Next we go to deal with the logic of NoteItemActivity. When creating a fragment, we need to call the NoteItemFragment.newInstance() method and pass in the NoteItem class.
Then modify the way of receiving parameters in NoteItemFragment:
Here we get the fragment argument method is relatively simple, just call the getArguments().getX() method directly.
Now we can click the corresponding list item to display the detailed content of the diary with the correct information. At this time, if we modify the content of the diary, then click Save to return.
First modify the button click event of NoteItemFragment:
Here we directly call the finish method of the managed Activity to destroy the current Activity. However, after returning to the diary list page, the RecyclerView view did not refresh, which is obviously not what we expected.
After NoteListFragment starts the NoteItemActivity instance, NoteItemActivity is placed on the top of the rollback stack. This causes the NoteListActivity instance at the top of the stack to be suspended and stopped. The user clicks the back button to return to the list item interface, and NoteItemActivity pops out of the stack and is destroyed. At this point NoteListActivity restarts immediately and resumes operation.
After NoteListActivity resumes operation, the operating system will issue an instruction to call the onResume() lifecycle method.
After NoteListActivity receives the instruction, its FragmentManager will call the fragment currently managed by the activity
’s onResume() method. The fragment here refers to NoteListFragment.
So we can update the UI by overriding the onResume() method of NoteListFragment.
Obviously we did not return the data change to NoteListFragment at this time, so we also need to receive the return value from NoteItemFragment.
Fragment has its own startActivityForResult(. ) method and onActivityResult(. ) method, but no setResult(. ) method. So if NoteItemFragment wants to return a value, it must rely on the setResult() method of the managed Activity.
NoteItemFragment modified code is as follows:
🐖: Here, EXTRA_NOTE is extracted into the file.
Then when starting the Activity, you need to call the startActivityForResult method of the fragment. It turns out that the code for us to start Activity is implemented in NoteListAdapter. For the convenience of us, we create an interface and implement it in fragment.
Create interface NoteListItemClickListener:
position is the index of the data item
NoteListAdapter modify the code as follows:
Next, we need to implement the fragment's onActivityResult method to receive the return value:
Then notify RecyclerView to update the data in the onResume method:
Here we are modifying a single diary record, so use notifyItemChanged to refresh a single NoteItem item in the list item
running result:
Even if the content of this article is over, the middle logic is not very clear, I hope everyone can understand it. . .
3.Установка Android SDK
Заходим на официальный портал для разработчиков Android. Скачиваем Android SDK и устанавливаем в удобную директорию.
После установки добавляем пути d:\tools\android\android-sdk\tools;d:\tools\android\android-sdk\platform-tools в системную переменную PATH
Разделы портала
6. Создаем тестовый проект
Создаем тестовый проект, используя проект существующего приложения. Для этого нажимаем правой клавишей мыши на проекте и выбираем Android Tools -> New Test Project
Получили еще один проект, но уже в нем будут храниться наши тесты.
Что пишут в блогах
Что пишут в блогах (EN)
5. Устанавливаем плагин для Eclipse
Для этого, на главном меню Eclipse, выбираем Help -> Install new software
Нажимаем Add и добавляем путь к репозиторию для установки
Устанавливаем Developer Tools
Перезапускаем среду разработки, чтобы продолжить.
Указываем путь к Android SDK в Eclipse IDE. Для этого нажимаем Windows -> Preferences
7. Подключаем библиотеку Robotium
Загружаем Robotium jar файл в удобную директорию. Последняя версия, на момент написания статьи, robotium-solo-3.1.jar.
Подключаем библиотеку к тестовому проекту. Правый клик мышкой на тестовом проекте -> Build Path -> Configure Build Path -> Add External JARs.
Все готово для начала автоматизации!
8. Пишем тесты
Создаем первый тестовый класс в пакете com.example.android.notepad.test. С вот таким содержимым
Самый простой тест на добавление новой заметки. Запускаем тест и проверяем результаты.
Много времени уходит на запуск эмулятора. Вы можете попробовать запускать тесты на своем Android телефоне, а так же создавать тесты без привязки к проекту приложения. Но об этом позже.
NotePad++ New
версия: 1.0.0
Последнее обновление программы в шапке: 06.12.2019
Краткое описание:
Простой и удобный блокнот для редактирования всех типов текста.
- Открывает любые текстовые файлы, включая java, html, c, hex, php, py, txt, doc и другие!
- Удобный и понятный интерфейс
- Возможность изменять кодировку
- Возможность сменить стиль шрифта, размер шрифта, цвет шрифта и цвет фона
- Нет ничего лишнего, без рекламы и вирусов!
- Специально для 4PDA! Вес программы- 130 кб!
- Полностью на русском языке! (Добавлен также английский на выбор)
- Сохраняет последний напечатанный файл, независимо, сохранили Вы его, или нет
- Возможность сделать ссылки и номера телефонов в тексте кликабельными!
Русский интерфейс: Да (Русский и Английский)
Требования: Android 2.1>
Разработчик: Я, NowenUI
Домашняя страница: NowenUI
Google Play: Cтарая версия (0.2.1) ||| Новая версия (1.0.0 и выше)
Пожалуйста, скачивайте с Google Play, так Вы меня поддержите.
- Возможность смены кодировки текста
- Исправлен трабл с сохранением текста на карту памяти
- Новая иконка программы
- Переписан исходных код
- Удалены все ошибки в приложении
- Переписан файловый менеджер в программе
- Более удобный интерфейс
- Новое название пакета приложения! ТРЕБУЕТ УДАЛЕНИЯ ПРЕДЫДУЩЕЙ ВЕРСИИ!
- Удалена неработающая функция кликабельности ссылок
Все Вы конечно хотите, чтобы моя программа часто обновлялась, появилась поддержка синтаксиса, появились номера строк, стили, много новых функций, появился мой официальный сайт. Но без Вашей помощи мне не обойтись.
Пожалуйста поддержите меня, просто купите полезную программу Custom HTC Pro с Google Play (Цена- 35 рублей). Если она Вам не понравится-удалите через 20 минут после покупки. Но я могу предположить, что эта программа будет полезна для обладателей телефонов HTC, она научит прошивать, оптимизировать, ускорять, изменять внешний вид данных телефонов.
Если бы ее купило всего 100 человек, я бы смог добавить поддержку синтаксиса, номера строк, стили, а также больше и чаще ее оптимизировать и обновлять. Если бы ее купило 200-300 человек, я бы смог открыть свой сайт с онлайн технической поддержкой, добавить много новых функций в программу, и возможно, приблизить ее к ПК версии и сделать бесплатной.
Заранее спасибо, друзья!
Вряд ли сейчас найдёшь человека, которому никогда не пригождался стандартный блокнот в телефоне. Например, когда он на срочном совещании, а записать информацию некуда. Именно в таких случаях пользователям и пригодится программа Notepad++ for Android. Нет, здесь не будет никаких инновационных возможностей, которые нигде раньше не встречались. Блокнот – сборник самых важных и нужных функций, которые сильно упростят вам жизнь.
Конференции
Heisenbug 2022 Spring
Большая техническая конференция по тестированию
Online — с 30 мая по 1 июня. Offline-день — 21 июня
Профессиональная конференция по автоматизации в тестировании и рядом
27 и 28 июня, Москва, Radisson Slavyanskaya.
Что пишут в блогах
Возможности
Настройки в Notepad++ гибки, богаты и разнообразны: переносы строк, размер и текст шрифта, ориентация. Помимо встроенных шрифтов можно установить дополнительные, которые после скачивания должны быть скопированы в нужную директорию. Для тех, кому нужно сохранять файлы в систему, была добавлена настройка системных папок. Если вам обязательно нужен счётчик символов, то вы обрадуетесь, когда узнаете, что он здесь есть. Блокнот полностью переведён на русский язык, так что трудностей при использовании интерфейса возникнуть не должно. Так как в утилите для Android есть планировщик, то к нему должны быть уведомления. Всё так и есть. Они тоже могут быть настроены под вкусы каждого, кто использует блокнот. Одним из главных плюсов приложения является отсутствие рекламы. Разработчики не стали добавлять её.
2. Установка Eclipse IDE
Скачиваем с официального сайта. Распаковываем в удобную директорию. Я устанавливаю в папку tools, где у меня находятся все инструменты касательно разработки (некоторые инструменты могут нестабильно работать из-за пробела в пути “Program Files”). Запускаем Eclipse
1. Установка Java
Как проверить установлена ли нужная версия java? Открываем консоль и пишем
java -version
Должны получить что-то вроде
Если же получаем
тогда нужно скачать дистрибутив и установить со стандартной конфигурацией.
Главные особенности
Notepad для Андроид поддерживает большинство доступных на данный момент кодировок (более 50), которые он определяет автоматически. Помимо стандартных расширений программа способна открыть и программные коды (html, java, php и т.д.). Файлы, созданные в приложении, хранятся в созданных заранее папках. Там же можно их сортировать, менять местами и делать всё что угодно. Чтобы писать заметки было веселее, присутствует выбор разнообразных фонов. Всего их 8. В главном меню есть возможность увидеть сразу несколько режимов: записки (список дел), список покупок, создание фото и видео заметок “рисовалка” в графическом редакторе. В последнем присутствует большое разнообразие цветов и фонов, поэтому эта функция является полезной. Пользователям не стоит бояться, что файлы пропадут, если вы их не сохраните. Блокнот имеет функцию автосохранения. Также есть виджет для рабочего стола, который тоже обладает гибкими настройками: смена фона, размера и стиля шрифта и многое другое. Отдельно стоит упомянуть добавление гиперссылок. Любые номера телефонов или ссылки станут кликабельными, если вы этого захотите. Для удобства в программу была добавлена возможность поиска по файлу. С её помощью не придётся долго искать определённое слово. А если вам нужен именно последний изменённый файл, то просто нажмите на него в соответствующем меню. Данные, находящиеся внутри Notepad’a, стоит защитить паролем. Помимо локального хранилища здесь также есть поддержка Дропбокса. Но эта функция доступна только при наличии клиента на устройстве.
Онлайн-тренинги
Совсем недавно прошел курс по автоматизации мобильных приложений. Чтобы немного помочь тем, кто не может принять участие в тренингах, я решил сделать небольшую вводную по работе с автоматизацией на Android. Начнем с установки нужных средств и написания простого теста.
Что нам для этого понадобится.
А теперь обо всем, по-порядку. Выполняйте действия в описаной последовательности и все получится! Но если что пошло не так - пишите комментарии к статье, будем разбираться.
4. Установка нужных платформ
Открываем ADB Manager и устанавливаем все платформы. Установка может занять несколько часов, зависимо от вашего канала связи.
5. Подготовка тестируемого приложения
За основу возьмем семпловое приложение из директории семплов Android SDK. Например Notepad.
Для начала создадим проект в Eclipse. File -> New -> Android Project
Указываем имя и выбираем Create project from existing sample
Выбираем API, например 7. На следующем окне выбираем приложение NotePad и нажимаем Finish.
Получаем созданный проект. Давайте запустим сборку приложения и проверим его функционал.
Ждем пока запустится эмулятор.
Это может занять от 1 минуты и иногда до 10ти. Эмулятор самое узкое место в написании программ под Android. В дальнейшем мы поговорим, какие есть альтернативы.
После запуска получаем наше приложение и можем ознакомиться с его функциональными возможностями.
Читайте также: