Найти тему
InnaTomeya

Создание почтового приложения. Часть 1.

Оглавление

Создадим с Вами почтовое приложение (ну на данном этапе только набросок)

Создаем новый проект

-2

Далее нам с Вами нужно создать фрагмент для Входящих сообщений (выделяем директорию java далее правой кнопкой мыши New-Fragment-Fragment(Blank).

-3

Так же мы будем создавать этим способом фрагменты для Черновика(Drafts), Отправленных(SentItems) и Мусора(Trash).

-4

Код fragment_inbox.xml

-5

Код InboxFragment.java

-6

Если какая-либо часть кода непонятна или забыта ее значение то переходите на статью https://innatomeya.ru/2022/11/16/знакомство-с-android-studio/

Код fragment_drafts.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical"

    tools:context=".DraftsFragment">

    <TextView

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        android:text="Черновики" />

</LinearLayout>

Код DraftsFragment.java

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

public class DraftsFragment extends Fragment {

    @Override

    public View onCreateView(LayoutInflater inflater, ViewGroup container,

                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment

        return inflater.inflate(R.layout.fragment_drafts, container, false);

    }

}

Код fragment_sent_items.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical"

    tools:context=".SentItemsFragment">

    <TextView

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        android:text="Отправленные" />

</LinearLayout>

Код SentItemsFragment.java

package com.example.chatghost;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

public class SentItemsFragment extends Fragment {

    @Override

    public View onCreateView(LayoutInflater inflater, ViewGroup container,

                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment

        return inflater.inflate(R.layout.fragment_sent_items, container, false);

    }

}

Код fragment_trash.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical"

    tools:context=".TrashFragment">

    <TextView

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        android:text="Мусор" />

</LinearLayout>

Код TrashFragment.java

package com.example.chatghost;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

public class TrashFragment extends Fragment {

    @Override

    public View onCreateView(LayoutInflater inflater, ViewGroup container,

                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment

        return inflater.inflate(R.layout.fragment_trash, container, false);

    }

}

Создадим панель инструментов, для включения в каждую активность проекта. В директории layout правой кнопки мыши New-Layout Resource File

-7

Код toolbar_main.xml

<?xml version="1.0" encoding="utf-8"?>

<androidx.appcompat.widget.Toolbar

    xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="?attr/actionBarSize"

    android:background="?attr/colorPrimary"

    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

</androidx.appcompat.widget.Toolbar>

Где android:layout_width="match_parent"

android:layout_height="?attr/actionBarSize" – Ширина панели инструментов равна ширине родителя, а высота панели приложения по умолчанию.

android:background="?attr/colorPrimary" - Фон панели инструментов будет в том же цвете, что и фон панели приложения.

android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"> - Назначение панели инструментов такое же оформление, как и у панели приложения.(для заметки NoActoinBar не оформляет панели приложений так, как это делает DarkAcrionBar.

В файлах themes.xml и themes.xml (night) оформляем стиль который нам нравиться.

Код themes.xml

<resources xmlns:tools="http://schemas.android.com/tools">

    <!-- Base application theme. -->

    <style name="Theme.ChatGhost" parent="Theme.MaterialComponents.DayNight.NoActionBar">

        <!-- Primary brand color. -->

        <item name="colorPrimary">@color/colorPrimary</item>

        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>

        <item name="colorAccent">@color/colorAccent</item>

        <!-- Secondary brand color. -->

        <item name="colorSecondary">@color/teal_200</item>

        <item name="colorSecondaryVariant">@color/teal_700</item>

        <item name="colorOnSecondary">@color/black</item>

        <!-- Status bar color. -->

        <item name="android:statusBarColor" tools:targetApi="21">?attr/colorPrimaryVariant</item>

        <!-- Customize your theme here. -->

    </style>

</resources>

Где "Theme.MaterialComponents.DayNight.NoActionBar" – Тема удаляет панель приложения по умолчанию и будет заменена нашей.

Код themes.xml (night)

<resources xmlns:tools="http://schemas.android.com/tools">

    <!-- Base application theme. -->

    <style name="Theme.ChatGhost" parent="Theme.MaterialComponents.DayNight.NoActionBar">

        <!-- Primary brand color. -->

        <item name="colorPrimary">@color/colorPrimary</item>

        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>

        <item name="colorAccent">@color/colorAccent</item>

        <!-- Secondary brand color. -->

        <item name="colorSecondary">@color/teal_200</item>

        <item name="colorSecondaryVariant">@color/teal_200</item>

        <item name="colorOnSecondary">@color/black</item>

        <!-- Status bar color. -->

        <item name="android:statusBarColor" tools:targetApi="21">?attr/colorPrimaryVariant</item>

        <!-- Customize your theme here. -->

    </style>

</resources>

Добавим наши цвета в colors.xml

Код colors.xml

<?xml version="1.0" encoding="utf-8"?>

<resources>

    <color name="purple_200">#FFBB86FC</color>

    <color name="purple_500">#FF6200EE</color>

    <color name="purple_700">#FF3700B3</color>

    <color name="teal_200">#FF03DAC5</color>

    <color name="teal_700">#FF018786</color>

    <color name="black">#FF000000</color>

    <color name="white">#FFFFFFFF</color>

    <color name="colorPrimary">#FF018786</color>

    <color name="colorPrimaryDark">#FF3700B3</color>

    <color name="colorAccent">#FF03DAC5</color>

</resources>

Создадим активности HelpActivity и FeedbackActivity в директории java

Код activity_help.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:app="http://schemas.android.com/apk/res-auto"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical"

    tools:context=".HelpActivity">

    <include layout="@layout/toolbar_main"

        android:id="@+id/toolbar"/>

    <TextView

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        android:text="Помощь"/>

</LinearLayout>

Код HelpActivity.java

package com.example.chatghost;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import androidx.appcompat.widget.Toolbar;

public class HelpActivity extends AppCompatActivity {

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_help);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);

    }

}

Код activity_feedback.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:app="http://schemas.android.com/apk/res-auto"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical"

    tools:context=".FeedbackActivity">

    <include layout="@layout/toolbar_main"

        android:id="@+id/toolbar"/>

    <TextView

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        android:text="Обратная_связь"/>

</LinearLayout>

Код FeedbackActivity.java

package com.example.chatghost;

import androidx.appcompat.app.AppCompatActivity;

import androidx.appcompat.widget.Toolbar;

import android.os.Bundle;

public class FeedbackActivity extends AppCompatActivity {

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_feedback);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);

    }

}

Добавим картинку для почтового приложения, в моем примере я добавила логотип (q.jpg)

-9

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

Код strings.xml (директория values)

<resources>

    <string name="app_name">ChatGhost</string>

    <string name="user_name">Ghost</string>

    <string name="nav_inbox">Входящие</string>

    <string name="nav_drafts">Черновики</string>

    <string name="nav_sent">Отправленные</string>

    <string name="nav_trash">Мусор</string>

    <string name="nav_support">Поддержка</string>

    <string name="nav_help">Помощь</string>

    <string name="nav_feedback">Обратная_связь</string>

</resources>

Создадим заголовок для навигационной панели.

В директории layout правой кнопкой мыши New-Layout Resource File

И присваиваем имя nav_header

Код nav_header.xml

<?xml version="1.0" encoding="utf-8"?>

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="180dp"

    android:theme="@style/ThemeOverlay.AppCompat.Dark">

    <ImageView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:scaleType="centerCrop"

        android:src="@drawable/q"/>

    <LinearLayout

        android:layout_width="wrap_content"

        android:layout_height="match_parent"

        android:orientation="vertical"

        android:gravity="bottom|start"

        android:layout_margin="16dp">

        <TextView

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="@string/app_name"

           android:textAppearance="@style/TextAppearance.AppCompat.Body1"/>

        <TextView

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="@string/user_name"/>

    </LinearLayout>

</FrameLayout>

Создание меню из двух разделов, сперва создадим поддиректорию menu в директории res, выделим res правой кнопкой мыши New-Directory (имя menu)

И в этой поддиректории создадим файл menu_nav.xml (правой кнопкой мыши New-Layout Resource File)

Код menu_nav.xml

<?xml version="1.0" encoding="utf-8"?>

<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <group android:checkableBehavior="single">

        <item android:id="@+id/nav_inbox"

            android:icon="@android:drawable/sym_action_email"

            android:title="@string/nav_inbox"/>

        <item android:id="@+id/nav_drafts"

            android:icon="@android:drawable/ic_menu_edit"

            android:title="@string/nav_drafts"/>

        <item android:id="@+id/nav_sent"

            android:icon="@android:drawable/ic_menu_send"

            android:title="@string/nav_sent"/>

        <item android:id="@+id/nav_trash"

            android:icon="@android:drawable/ic_menu_delete"

            android:title="@string/nav_trash"/>

   </group>

<item android:title="@string/nav_support">

        <menu>

            <item android:id="@+id/nav_help"

                android:icon="@android:drawable/ic_menu_help"

                android:title="@string/nav_help"/>

            <item android:id="@+id/nav_feedback"

                android:icon="@android:drawable/sym_action_email"

                android:title="@string/nav_feedback"/>

        </menu>

    </item>

</menu>

Пишем полную разметку для activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:app="http://schemas.android.com/apk/res-auto"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:id="@+id/drawer_layout"

    tools:context=".MainActivity">

    <LinearLayout

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        android:orientation="vertical">

        <include layout="@layout/toolbar_main"

            android:id="@+id/toolbar"/>

        <FrameLayout

            android:layout_width="match_parent"

            android:layout_height="match_parent"

            android:id="@+id/content_frame"/>

    </LinearLayout>

    <com.google.android.material.navigation.NavigationView

        android:layout_width="wrap_content"

        android:layout_height="match_parent"

        android:id="@+id/nav_view"

        android:layout_gravity="start"

        app:headerLayout="@layout/nav_header"

        app:menu="@menu/menu_nav"/>

</androidx.drawerlayout.widget.DrawerLayout>

Где NavigationView – Определяет внешний вид панели навигации и часть ее поведения.

Последнее что нам нужно сделать это добавить InboxFragment в MainActivity

Код MainActivity.java

package com.example.chatghost;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import androidx.appcompat.widget.Toolbar;

import androidx.fragment.app.Fragment;

import androidx.fragment.app.FragmentTransaction;

public class MainActivity extends AppCompatActivity {

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);

        Fragment fragment = new InboxFragment();

        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();

        fragmentTransaction.add(R.id.content_frame,fragment);

        fragmentTransaction.commit();

    }

}

В Telegram канале находятся проекты

https://t.me/innatomeya_STM32_Linux