Android one user interface

How to Create User Interface Login & Register with Android Studio

ok, this is my first article in Medium. In this section, I want to share with you about the User Interface on Android and we will create a Login page and a Register page. Some components that I will use:
1. Viewpager
2. Fragment
3. Edittext
4. Button
5. Textview
6. Imageview

What about the results? let’s coding (follow step by step)

  1. Of course we must already have an Android Studio. if not, you can download it first on the official Android Studio website. If you already have one, please open your Android studio.

2. We create a new project by clicking “Start a new Android Studio project”. Fill in the application name column with “LoginApp”, then click next.

3. Select the minimum SDK you need or want, then click next.

4. Select “Empty Activity” and click next. After that, the “Activity Name” and “Layout Name” columns will appear, in this section just leave it like that, then click finish.

After you click finish, Android Studio will make you an Application with the name “LoginApp”.

After the application is successfully built, you can simply make adjustments to the following sections:

Open the colors.xml file in app/res/values/colors.xml, and change it like this:

Create a folder with the name “font” in the res folder, by right clicking on the res directory, select new / directory and name it “font”. After that, copy this font into font directory. (download the font 1 and font 2).

Create some Drawable Resource File in the drawable directory, by right-clicking on the drawable directory, select new / Drawable Resource File.

After that open file styles.xml and change like this :

Add the theme property in the Main Activity in the manifest, in the app / manifests / AndroidManifest.xml folder

So the AndroidManifest.xml file will be as follows:

After all the steps above are done, then make 2 fragments with the name fragment_login and fragment_register in the layout directory, by right-clicking on the layout directory, New/Fragment/Fragment (Blank)

Uncheck:
include fragment factory methods? and include interface methods?

Adjustment of several layouts :

change the activity_main.xml layout, fragment_login.xml and fragment_register.xml so that it will be as below

Open the strings.xml file in the res / values / strings.xml directory and change it to something like the following :

So that the overall structure of the project will be as follows :

Connect fragments with viewpager

Create an inner class in the MainActivity.java class with the name AuthenticationPapterAdapter. This class is a derivative of the FragmentPagerAdapter class and serves to connect Fragments with ViewPager,

Then call the class in the onCreate() method in MainActivity.java and connect with viewpager

So the MainActivity.java class will be like this

The display of the final application will be like this

Источник

Jetpack Compose — как легко построить UI на Android

В июле этого года вместе с Android Studio Arctic Fox вышла одна из долгожданных библиотек — Jetpack Compose. Она позволяет создавать пользовательский интерфейс в декларативном стиле и обещает быть революцией в построении UI.

Читайте также:  Создание vpn подключения android

Разбираемся, так ли это на самом деле, какие у библиотеки преимущества и недостатки. Подробности — в статье.

Преимущества Jetpack Compose

Jetpack Compose — это набор инструментов для разработки UI в Android-приложении. Он призван ускорить и упростить разработку пользовательского интерфейса, избавить от лишнего кода и соединить модель реактивного программирования с лаконичностью Kotlin.

Сразу с места в карьер — какие есть преимущества у библиотеки:

1. Меньше кода. Jetpack Compose позволяет писать меньше кода, а значит разработчик может больше фокусироваться на проблеме, с меньшим количеством тестов и дебага, а значит и багов.

2. Интуитивно понятный. Compose использует декларативный API — разработчику нужно лишь сказать, что сделать, а все остальное ляжет на плечи библиотеки.

3. Удобство внедрения. Compose совместим с любым существующим кодом. Например, можно вызвать Compose-код из вьюх (view) и, наоборот, вьюхи из Compose. Многие библиотеки вроде Jetpack Navigation, ViewModel и Coroutines уже адаптированы под Compose, что позволяет сравнительно быстро внедрить его в свой код. Кроме того, Android Studio Arctic Fox поддерживает превью создаваемых вьюх.

4. Имеет обширный инструментарий. Jetpack Compose позволяет создавать красивые приложения с прямым доступом к Android Platform API и build-in поддержкой Material Design, тёмной темы, анимаций и других крутых штук.

Далее пройдёмся по основным аспектам библиотеки и посмотрим, как сильно повышается производительность приложения.

Подключение к проекту

Чтобы подключить Jetpack Compose к проекту, необходимо указать некоторые строки кода в своем build.gradle.

В рутовом объявим переменную с версией Compose:

Здесь мы указываем, что в проекте будем использовать Jetpack Compose и объявляем необходимые зависимости (подробнее про зависимости можно почитать в официальном гайде).

Дальше всё просто. В активити (activity) объявлем Composable-функцию, строим иерархию вьюх с указанием необходимых атрибутов и смотрим результат.

Пройдемся по коду. Я написал две реализации вёрсток различной сложности:

1. Простая реализация

Добавляет TextView в вёрстку с текстом с конкатенацией Hello и аргумента, переданного в Greeting.

Важно отметить, что имена Composable-функций начинаются с заглавной буквы. Это соглашение по наименованию функций, поэтому если писать со строчной, то студия будет подсвечивать неверный нейминг.

2. Более сложная реализация

Этот вариант представляет собой скролящийся экран, который содержит изображение, текст и кнопку. Рассмотрим некоторые особенности:

Необходимо объявить Scroll State. Только не обычный, а тот, который позволяет сохранять состояние скролла сквозь рекомпозицию — rememberScrollState().

Column представляет собой ViewGroup с вертикальным расположением элементов.

Modifier позволяет управлять атрибутами, добавлять декорации и поведение к вьюхам.

Остальное интуитивно понятно. И это как раз одна из ключевых особенностей Jetpack Compose — даже если вы не использовали библиотеку ранее, то всё равно с ней разберётесь.

Добавить вьюхи в активити можно через extension setContent <>, например:

В общем-то, создание UI выглядит действительно просто. Теперь определим, насколько сильно оптимизируется приложение и как быстро пользователь увидит окончательный экран.

Для тестирования воспользуемся библиотекой Jetpack Benchmark, о которой, кстати, тоже рассказывали в отдельной статье. Код теста выглядит так:

Протестируем три версии установки вьюхи в активити:

При передаче ресурса в setContentView.

При передаче вьюхи в setContentView.

Итоги тестирования можно посмотреть в таблице: левый столбец — название теста, правый — время на выполнение:

Источник

User Interface (UI) Design in Android App

How to Develop User Interface (UI) in Android App?

This tutorial explains how to design User Interface (UI) for Android Android Application. It’s one of the more fun and also one of the more easier to understand topics.

What is (User Interface) UI in Android?

User Interface in an Android Application can be build using the layouts (ViewGroup objects) and widgets (View objects).

Читайте также:  Horizon chase turbo android

Various types of pre-installed UI components like the structured layout, objects and UI controls are provided in Android Studio which enables user to build a Graphical User Interface (GUI) for their Android app.

UI modules for special interfaces like dialog box, notifications box, menus etc are also provide by Android

Please follow the steps below in order to design UI (User Interface) for Android

So from here what I want to do is — click start a new Android studio project.

And you can actually name this — anything you want for example I’m going to name mine ‘Hamblaster’.

This is still good, we are still making something through the phone. Now, instead choosing the blank activity, what this would do is it would make that one default blank screen, but I wanna show you guys how to add activities manually. So, instead of that choose to add no activity.

So, when you click finish what’s gonna happen is it’s gonna load up and you’re pretty much gonna have an empty, completely empty project. I meanit’ss gonna have those core files, but check it out. Alright, so when it’s done setting up this is what you get.

Now, obviously if we click on project on the left-hand side, we can see that it does indeed have some files created for us but definitely no activities or screens anywhere and well, our app would be pretty stinking useless if the user didn’t have any screen to look at.

So let’s go ahead and do that first. So, make sure you’re in Android view, you can actually look at project view if you want, but I’m gonna be in Android view.

and in your app expand that and go to java, expand that as well and now remember this is where we are gonna be building the activity, if you remember from last time, this is actually where that file was.

So now, if you right click it and select new; scroll down to activity and we’ll just choose blank activity.

So again, once we’re looking at the screen — what this is, is basically if we click blank activity whenever we are setting up our project then this is where we would be but that’s how you do it manually and also whenever you add additional activities to whatever projects you’re working on in the future that’s how you do it.

Now, for right now, this example is only going to have one activity so I really don’t need to give anything like a name because I’m not really gonna get disorganised with one activity. However, since this is the only activity, its very important that you choose this — launcher activity.

Now, remember, the launcher activity is the very first screen that whenever android is trying to open your app its gonna look for this. So, without it if you have a bunch of activities and none of them are the launcher activity, then your app is not going to open correctly.

So, since this is your only activity we need to make it the launcher activity, aka the starting point.

So as soon as you create an activity what android studio is gonna do is it’s gonna create those 2 files first.

Читайте также:  Вайбер для андроид не устанавливается

Below is the main activity, the job of the brains behind our activity.

And the interface.

No need to discuss everything because you guys already know what all that means. So, one other thing I want to point out is that there was one more thing that all of my activities had to be taken care of in the manifest so just look at the manifest and you probably have to do something here — open and check it out — Android studio actually took care of all of that for us, whenever we just created that new activity.

Again in the manifest, this is where all your activities have to be declared, it did everything for us. That is one of the reasons I love Android Studio.

Now just close out of that and we can continue with the good stuff. So over an ‘activity_main.xml’ the first thing I want to do is delete this little thing right here — this text.

So just go ahead select it like before and just delete it.

Now, just for this example, this is just to demonstrate a few things, so I’m building the very first page to the social network so what we need are a couple of things.

The first thing is this ‘Large Text’.

Alright, so that’s a little bit easier to read, I’m just gonna organize everything before I start customizing any of these widgets. So drag in ‘Large Text’ — it’ll say — “sign in or log in”, so this will be the log in screen. So under this, of course, we need two little input areas for the user to enter their log in information — an email and a password. So first, lets get the email, we should go down, its actually under text fields, so click that if its not expanded and for email — just drag that over and we can tell when its aligned with the middle because of this little green line. So drop that right there.

Alright looks pretty good. Now, under here we will have a password field, so drag that and drop it.

Now of course, if I was actually designing this then what I would do is I would have to make a little text area here that says — email and password. But for right now, just demonstrating some stuff.

Now, after they are done typing in their information they need some button to click on, so if you scroll way back up, its no way back up — its like 2 inches away but we are going to select this button and drag it right underneath here and you know what actually align this in the dead center of your app by using those little alignment things and alright, looking pretty good.

So, what I wanna do now, is I actually wanna change the text on this right here and also on the button.So select this ‘Large Text’,

and if we scroll down to a property called Text then what we can see is, it says ‘Large Text’ that’s the text that displays, what we actually wanna do is click on this and we’ll change it to something like ‘Sign In’ and hit enter.

Источник

Оцените статью