- Рисование собственных представлений (View) в Android
- Получите полный контроль над представлением и оптимизируйте его производительность
- Введение
- Общий подход
- Обновление представления
- invalidate()
- requestLayout()
- 40 Best Free And Open Source Android Apps in 2021
- Free and Open Source Operating System
- Free and Open Source Search Application
- Free and Open Source Calendar Application
- Free and Open Source Calculator Application
- Free and Open Source Weather Application
- Free and Open Source Camera Application
- Free and Open Source Home Launcher Applications
- Free and Open Source Habit Tracker Application
- Free and Open Source Web Browsers
- Free and Open Source E-Mail Services & Application
- Free and Open Source SMS Application
- Free and Open Source Video Streaming Application
- Free and Open Source Video Player Application
- Free and Open Source Note Taking Application
- Free and Open Source Maps Application
- Free and Open Source Instant Messenger Applications
- Free and Open Source VPN Applications
- Free and Open Source Home Media Streaming/Entertainment Hub Application
- Free and Open Source Social Networking Application
- Free and Open Source Blogging Application
- Free and Open Source Clipboard Manager Application
- Free and Open Source Text Editor Application
- Free and Open Source Music Player Applications
- Free and Open Source Gallery Application
- Free and Open Source Pedometer Application
- Free and Open Source Samsung Gear Fit Application
- Free and Open Source Android Apps Market Application
- Free and Open Source Reddit Client Applications
- Free and Open Source File Manager Application
- Free and Open Source Document Viewer/Office Suite Application
- Free and Open Source Flash Tool Application
- Free and Open Source Reference Site/Encyclopaedia Application
- Free and Open Source Task Management Application
- Free and Open Source Podcast Manager+Player Application
- Free and Open Source Flashlight Application
- Free and Open Source Bitcoin and Ether Wallet Application
- Free and Open Source GitHub Client Application
- Conclusion
Рисование собственных представлений (View) в Android
Получите полный контроль над представлением и оптимизируйте его производительность
В преддверии старта курса «Android Developer. Professional» приглашаем всех желающих принять участие в открытом вебинаре на тему «Пишем gradle plugin».
А пока делимся переводом полезного материала.
Введение
Разработчики постоянно проектируют различные виды пользовательских интерфейсов с помощью XML, но в дополнение к этому можно довольно легко освоить создание собственных представлений, которые открывают новые преимущества и позволяют избежать повторного использования шаблонного кода.
В Android доступен широкий набор готовых виджетов и макетов для создания пользовательского интерфейса, однако они не могут удовлетворить все требования наших приложений. И здесь на помощь приходит возможность создания собственных представлений. Создав собственный подкласс представления, можно получить максимально полный контроль за внешним видом и функционалом экранного элемента.
Прежде чем приниматься за работу с собственными представлениями, полезно изучить жизненный цикл представления.
Зачем создавать собственные представления?
Чтобы реализовать собственное представление, в большинстве случаев понадобится больше времени, чем если использовать обычные представления. Создавать собственные представления стоит лишь в том случае, если нет другого, более простого способа реализовать нужную вам возможность или если у вас есть какие-либо из указанных ниже проблем, которые можно устранить за счет создания собственного представления.
Производительность: в вашем макете много представлений и вы хотите оптимизировать их, нарисовав одно, более легкое собственное представление.
Имеется сложная иерархия представлений, которую трудно использовать и поддерживать.
Необходимо создать специализированное представление, требующее рисования вручную.
Общий подход
Чтобы приступить к созданию компонентов для реализации собственных представлений, необходимо выполнить следующие основные шаги.
Создать класс, расширяющий базовый класс или подкласс представления.
Реализовать конструкторы, использующие атрибуты из XML-файла.
Переопределить некоторые методы родительского класса (onDraw(), onMeasure() и т. д.) в соответствии с нашими требованиями.
После выполнения этих шагов созданный расширяющий класс можно использовать вместо представления, на основе которого он был создан.
Пример
В одном из моих проектов мне нужно было создать круглый виджет TextView для отображения количества уведомлений. Чтобы достичь этой цели, нужно создать подкласс TextView.
Шаг 1. Создадим класс с именем CircularTextView .
Шаг 2. Расширим класс виджета TextView. Здесь под TextView в IDE выдается ошибка, в которой сообщается, что у этого типа есть конструктор и он должен быть инициализирован.
Шаг 3. Добавим конструкторы в класс.
Это можно сделать двумя способами.
Первый способ добавления конструкторов в класс показан ниже.
Другой способ заключается в добавлении аннотации @JvmOverloads к вызову конструктора, как показано ниже.
Часто нас сбивает с толку то, что у представления есть несколько разных типов конструкторов.
View(Context context)
Простой конструктор для динамического создания представления из программного кода. Здесь параметр context — это контекст, в котором работает представление и через который можно получить доступ к текущей теме, ресурсам и т. д.
View(Context context, @Nullable AttributeSet attrs)
Конструктор, который вызывается при формировании представления из XML-файла. Он вызывается, когда представление создается из XML-файла, содержащего атрибуты представления. В этом варианте конструктора используется стиль по умолчанию (0), поэтому применяются только те значения атрибутов, которые есть в теме контекста и заданном наборе AttributeSet .
Шаг 4. Самый важный шаг в отрисовке собственного представления — это переопределение метода onDraw() и реализация необходимой логики отрисовки внутри этого метода.
Метод OnDraw (canvas: Canvas?) имеет параметр Canvas (холст), с помощью которого компонент представления может отрисовывать себя. Для рисования на холсте необходимо создать объект Paint.
Как правило, процесс рисования определяется двумя аспектами:
что рисовать (определяется объектом Canvas);
как рисовать (определяется объектом Paint).
Например, Canvas предоставляет метод для рисования линии, а Paint предоставляет методы для определения цвета этой линии. В нашем случае объект Canvas в классе CircularTextView предоставляет метод для рисования окружности, а объект Paint заполняет ее цветом. Проще говоря, Canvas определяет, какие фигуры можно нарисовать на экране, а Paint определяет свойства нарисованных фигур — цвет, стиль, шрифт и т. д.
Давайте займемся кодом. Мы создаем объект Paint и присваиваем ему некоторые свойства, а затем рисуем фигуру на холсте (объект Canvas), используя наш объект Paint. Метод onDraw() будет выглядеть так:
IDE показывает предупреждение о том, что следует избегать выделения объектов во время операций отрисовки или операций с макетом. Это предупреждение возникает потому, что метод onDraw() много раз вызывается при отрисовке представления, в котором каждый раз создаются ненужные объекты. Поэтому, чтобы избежать ненужного создания объектов, мы вынесем соответствующую часть кода за пределы метода onDraw() , как показано ниже.
При выполнении отрисовки всегда помните о том, что следует повторно использовать объекты вместо создания новых. Ваша IDE может указать на потенциальные проблемы, но полагаться на нее не стоит. Например, она не сможет отследить случай, когда объекты создаются внутри методов, вызываемых из метода onDraw() . Поэтому лучше проверять все самостоятельно.
Шаг 5. Мы закончили с рисованием. Теперь давайте внесем этот класс представления в XML.
Добавьте этот XML-макет в вашу активность (Activity) и запустите приложение. Вот что будет на экране.
Выглядит неплохо, правда? Теперь сделаем так, чтобы значение динамическому свойству цвета в circlePaint назначалось из активности, а также добавим контур к кружку. Для этого в классе CircularTextView необходимо создать несколько методов-сеттеров, чтобы можно было вызывать эти методы и устанавливать свойства динамически.
Для начала давайте реализуем настройку цвета отрисовки. Для этого создадим сеттер, как показано ниже.
Теперь мы можем устанавливать цвет из нашей активности динамически, вызывая этот метод.
Неплохо, правда? Теперь давайте добавим контур к кружку. Контур будет задаваться двумя входными параметрами: шириной линии контура и ее цветом. Чтобы задать цвет линии контура, нам нужно создать объект Paint точно так же, как мы это делали для кружка. Чтобы задать ширину линии контура, мы создадим переменную, установим для нее нужное значение и используем его в методе onDraw() . Полный код будет выглядеть так:
Теперь в активности можно динамически настраивать эти атрибуты нужным образом.
Далее давайте запустим приложение, устанавливая различные цвета для нашего виджета.
Итак, теперь стало ясно, как динамически устанавливать свойства из активности, но возникает вопрос о том, как устанавливать атрибуты из XML. Продолжим наше исследование.
Для начала создадим файл с именем attrs.xml в папке values. Этот файл будет содержать все атрибуты для различных представлений, которые мы создаем сами. В приведенном ниже примере у нашего представления под названием CircularTextView имеется атрибут ct_circle_fill_color , который принимает значение цвета. Аналогичным образом мы можем добавить и другие атрибуты.
Затем нам нужно будет прочитать эти свойства в классе, который мы создали для реализации собственного представления. В блоке инициализации мы считываем набор атрибутов, как показано ниже.
Теперь просто переходим к XML-макету и устанавливаем значение свойства, соответствующее нужному цвету, после чего запускаем приложение. На выходе мы увидим нужный результат.
В моем случае результат был таким:
Примечание. При рисовании не задавайте жестко размер вашего представления, так как им могут воспользоваться другие разработчики с применением других размеров. Рисуйте представление в соответствии с его текущим размером.
Обновление представления
Итак, мы задали собственное представление. Если мы хотим обновлять представление при изменении какого-нибудь свойства или по какой-то другой причине, этого можно добиться двумя основными способами.
invalidate()
invalidate() — это метод, который инициирует принудительную перерисовку определенного представления. Проще говоря, метод invalidate() следует вызывать в случае, когда требуется изменение внешнего вида представления.
requestLayout()
Если в какой-то момент происходит изменение состояния представления, то метод requestLayout() сообщает системе представлений, что необходимо сделать перерасчет фаз «измерение» (Measure) и «макет» (Layout) для данного представления (измерение → макет → рисование). Проще говоря, метод requestLayout() следует вызывать в случае, когда требуется изменение границ представления.
Теперь, я надеюсь, вы знаете в общих чертах, как создавать собственные представления. Чтобы они демонстрировали отличную производительность, необходимо освоить все описанные здесь методы.
Источник
40 Best Free And Open Source Android Apps in 2021
Updated: January 30, 2021 By Antony Agnel 3 Comments
Hey there, you might be wondering what are the best free and open-source Android apps alternatives to most of the applications and services available on your Android-powered device. As you know already, Android development is under the control of Google – the king of online behavioral tracking which also specializes in targeted advertising.
According to Wikipedia, Android OS is actually open-source but in ‘most’ devices it comes with proprietary components embedded with it. What does that mean? Is it really open source?
The answer is a big ‘NO’!
Well, I was also wondering the same and was looking for free & open-source alternatives to the conventional Android operating system, the apps, and services, etc.
Table of Contents
Free and Open Source Operating System
To obtain primary freedom from all things Google, we can make use of custom ROMs like LineageOS, AOKP, Resurrection Remix OS, etc. These operating systems are licensed under free and open-source licenses and are based on Android, that is – they are developed as free and open-source software but are based on the official Android versions released by Google.
Now, here are some free open source apps for Android –
Free and Open Source Search Application
First of all, the default Google Search app can be replaced with DuckDuckGo. DuckDuckGo claims itself as the search engine that doesn’t track you, unlike Google which uses filter bubbles for personalized search results. Moreover, some of DDG’s source code is free software hosted at GitHub under the Apache 2.0 License, but the core is proprietary.
Free and Open Source Calendar Application
Utilities like Google Calendar can be replaced with Etar.
Etar is a material design calendar based on the AOSP (Android Open Source Project) calendar.
Free and Open Source Calculator Application
The best open source calculator app available out there is the Calculator N+ Math Solver app.
Free and Open Source Weather Application
Good Weather for Android provides detailed weather in more than 200.000 cities and any geo-locations.
Free and Open Source Camera Application
Open Camera is a fully-featured and completely free camera app for Android phones and tablets.
Free and Open Source Home Launcher Applications
Google Now launcher or any other proprietary stock launcher can be replaced with Rootless Pixel Launcher (highly recommended), Lawnchair Launcher, Turbo Launcher or Open Launcher.
These launchers are freely available for anyone to use. They also allow you to personalize dozens of different elements on any android device so that you can have a home screen designed in your own unique style.
Free and Open Source Habit Tracker Application
Loop habit tracker application helps you to create and maintain good habits, allowing you to achieve your long-term goals. Detailed graphs and statistics show you how your habits have improved over time. This app is completely ad-free and open source.
Free and Open Source Web Browsers
We can replace Google Chrome with either Firefox Focus or Brave Web Browser.
Firefox is a free and open-source browser developed by the Mozilla Foundation and its subsidiary, the Mozilla Corporation.
Free and Open Source E-Mail Services & Application
Also, we can switch from Gmail to ProtonMail so that we can get rid of Gmail completely.
According to their official website, ProtonMail is the world’s largest secure email service, developed by CERN and MIT scientists. Also, they released the source code for the web interface under an open-source license. It’s quite easy to shift from Gmail to ProtonMail and forward all the new messages from the Gmail ID to the new ProtonMail ID. Check out this for step by step instructions on how to migrate completely to ProtonMail.
Moreover, they guarantee privacy, end-to-end encryption, anonymous email and what more – it’s 100% free!
Free and Open Source SMS Application
QKSMS brings a refreshingly beautiful and responsive material design touch to the stale state of text messaging. In a world with clunky SMS and MMS apps cluttered with bloat and ads, QKSMS is something to get excited about.
Free and Open Source Video Streaming Application
Next, we can replace YouTube with NewPipe.
NewPipe is a free and open-source YouTube client that doesn’t use any libraries that are dependent on Google’s framework or any YouTube API. It also lets you download YouTube videos with total privacy. The best part is that it lets you stream music in the background and do practically anything you can do with the official YT client.
Free and Open Source Video Player Application
The VLC media player is a free and open-source cross-platform multimedia player that plays most multimedia files as well as discs, devices, and network streaming protocols.
Free and Open Source Note Taking Application
Google Keep can be replaced with Orgzly | Notes & To-Do Lists
Currently, Orgzly is not an open-source project. Since the majority of its users are Org-mode users or users of other free software, it is the most commonly asked question. But in case it becomes free, the codes can be expected in GitHub repositories.
Free and Open Source Maps Application
Chuck out Google Maps and replace it with OsmAnd Maps (OpenStreetMap Automated Navigation Directions)
It is a free and open-source, global mobile map viewing and navigation app for offline and online maps for Android and iOS. It uses the OpenStreetMap (OSM) map database for its primary displays. The development of this project is being done on GitHub and the Android version is available under the GPLv3 license.
Free and Open Source Instant Messenger Applications
Remember, WhatsApp was bought out by Facebook for a whopping $22 Billion during 2014. Why spend so much for just an instant messaging app with no Ads? Give it a thought and if you could come up with a proper answer, please do mention it in the comments section of this post!
Signal Private Messenger is a free and open-source application for phones, that employs end end-to-end encryption and allows users to send end-to-end encrypted groups, text, pictures, and video messages and have encrypted phone conversations between Signal users on iPhone and Android. It is licensed under GPLv3.
Free and Open Source VPN Applications
OpenVPN for Android is an open-source client based on the open-source OpenVPN project. It uses the VPNService API of Android 4.0+ and does not require root access on your smartphone.
Free and Open Source Home Media Streaming/Entertainment Hub Application
Kodi® media center is an award-winning free and open source cross-platform software media player and entertainment hub for digital media for HTPCs (Home theater PCs). It uses a 10-foot user interface designed to be a media player for the living-room, using a remote control as the primary input device. Its graphical user interface (GUI) allows the user to easily browse and view videos, photos, podcasts, and music from a hard disk, optical disc, local network, and the internet using only a few buttons.
Free and Open Source Social Networking Application
We can try to migrate from Facebook to diaspora* – a privacy-aware, distributed, open-source social network.
It is a non-profit, user-owned social network that is based on the free Diaspora software. It consists of a group of independently owned nodes (called pods) that interoperate to form the network. It is not owned by any one person or entity, keeping it from being subject to corporate take-overs or advertising.
Free and Open Source Blogging Application
WordPress for Android puts the power of publishing in your hands, making it easy to create and consume content. Write, edit, and publish posts to your site, check stats, and get inspired with great posts in the Reader. WordPress for Android supports WordPress.com and self-hosted WordPress.org sites running WordPress 3.5 or higher and is a free and open-source blogging tool.
Free and Open Source Clipboard Manager Application
Clip Stack can remember all your clipboard history and recover text after reboot. It’s a clipboard manager, a user-friendly notebook and maybe a tiny GTD manager. You can easily copy, share, star, delete and merge every text.
Free and Open Source Text Editor Application
Ted is an open-source, ad-free, lightweight text editor, meant as a notepad application and not meant to edit big files. You can create a new text file, open existing files and of course save them. You can also display line numbers and open recent files. You can also search for text inside the opened file.
Free and Open Source Music Player Applications
Google Play Music can be replaced by Vanilla Music.
The vanilla Music player is a GPLv3 licensed MP3/OGG/FLAC/PCM player for Android with the following features – multiple playlist support, grouping by artist/album or genre, plain filesystem browsing, ReplayGain support, headset/Bluetooth controls, accelerometer/shake control, cover art support and ScrobbleDroid support for Last.fm integration.
Another very good alternative is the Shuttle Music Player.
Free and Open Source Gallery Application
The Simple Gallery is a simple tool that can be used for viewing photos and videos. Items can be sorted by date, size, name both ascending or descending and photos can be zoomed in. Media files are shown in multiple columns depending on the size of the display, you can change the column count by pinch gestures. They can be renamed, shared, deleted, copied, moved. Images can also be cropped, rotated, flipped or set as wallpaper directly from the app.
Free and Open Source Pedometer Application
This lightweight Pedometer app uses the hardware step-sensor for minimal battery consumption. This app is designed to be running all the time without having any impact on your battery life. It uses the hardware step detection sensor of devices like the Nexus 5, which is already running even when not using any pedometer app. Therefore the app does not consume any additional battery juice. Unlike other pedometer apps, this app does not track your movement or your location so it doesn’t need to turn on your GPS sensor.
Free and Open Source Samsung Gear Fit Application
Open Fit is an open-source alternative to the Gear Fit Manager and allows non-Samsung phones to use and control the Samsung Gear Fit. It currently provides most of the features provided by the Gear Fit Manager application and some new features.
Free and Open Source Android Apps Market Application
Google Play Store itself can be replaced with F-Droid, a free and open-source Android app repository.
F-Droid is a robot with a passion for Free and Open Source (FOSS) software on the Android platform. F-Droid has an Android client to perform installations and updates, and news, reviews and other features covering all things Android and software-freedom related.
Free and Open Source Reddit Client Applications
RedReader and Reddinator are two unofficial yet open-source Android clients for Reddit: the front page of the internet.
Free and Open Source File Manager Application
Dir is a simple, beautiful, free and open-source file manager for your Android smartphone.
Free and Open Source Document Viewer/Office Suite Application
Google Docs and Microsoft Office Suite can be ditched and can be replaced by LibreOffice Viewer.
LibreOffice is the world’s most popular Open Source office app. It uses the same engine as LibreOffice for Windows, Mac, and Linux. This, combined with a new front-end based on Firefox for Android, reads documents similarly to LibreOffice Desktop.
Free and Open Source Flash Tool Application
The Rootr app (requires root) helps you to flash and backup your device recovery and kernel without rebooting it very fast and easily without a PC or any outside influence.
Free and Open Source Reference Site/Encyclopaedia Application
The official Wikipedia Android app is designed to help you find, discover, and explore knowledge on Wikipedia.
Free and Open Source Task Management Application
OpenTasks is an open-source task app in material design. This app supports basic task management and provides a user-friendly user interface. To complete a task in the list view, just hold it for a moment and fling it from the left to the right. To edit a task fling it from the right to the left.
Free and Open Source Podcast Manager+Player Application
AntennaPod is a podcast manager and player that gives you instant access to millions of free and paid podcasts, from independent podcasters to large publishing houses such as the BBC, NPR, and CNN. Add, import and export their feeds hassle-free using the iTunes podcast database, OPML files or simple RSS URLs. Save effort, battery power and mobile data usage with powerful automation controls for downloading episodes (specify times, intervals and WiFi networks) and deleting episodes (based your favorites and delay settings).
Free and Open Source Flashlight Application
Minimal Open Source Flashlight is a minimalistic flashlight application. It consists of only one switch to turn the camera LED on and off – not more, no widget, no timer, no colored display, and no unnecessary artwork. Its size is just 39KB!
Free and Open Source Bitcoin and Ether Wallet Application
Blockchain Wallet helps you keep your bitcoin and ether safe, simple, and fun. It helps you to securely store your funds and instantly transact with anyone in the world. Join more than 17 million Blockchain wallet users – access your existing wallet on your Android device or create a new one. It’s free and takes just a few seconds.
Free and Open Source GitHub Client Application
FastHub for GitHub is yet another open-source unofficial GitHub client app but unlike any other app, FastHub is built from the ground up.
Conclusion
That’s all for now. Currently, I’m hunting for more FOSS applications; I will update the list as and when I come across new alternatives.
Hope this list helps someone in search of free and open-source alternatives to the traditional proprietary apps and services available in Google’s Play Store.
Источник