O Navigation Drawer é um componente que permite construir um menu lateral que desliza no sentido esquerda para a direita. É possível criar um Navigation Drawer do zero, mas atualmente, é disponibilizado o template pronto do Navigation Drawer quando você cria um projeto no Android Studio. Dessa forma, o trabalho fica compreendido em entender as funções de vários elementos que o compõe. Isto pode ser visto logo a seguir nos exemplos práticos.

Para mais detalhes:

Exemplo prático 1:

  • string.xml

    <resources>
        <string name="app_name">NavDrawerSimples</string>
        <string name="navigation_drawer_open">Abrir menu</string>
        <string name="navigation_drawer_close">Fechar menu</string>
        <string name="flamengo">Flamengo</string>
        <string name="corinthians">Corinthians</string>
        <string name="goias">Goiás</string>
    </resources>
  • colors.xml

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <color name="black">#FF000000</color>
        <color name="white">#FFFFFFFF</color>
        <color name="green">#8BC34A</color>
    </resources>
  • nav_menu.xml (pasta menu)

    <menu xmlns:android="http://schemas.android.com/apk/res/android">
        <item
            android:id="@+id/nav_flamengo"
            android:icon="@drawable/ic_launcher_foreground"
            android:title="@string/flamengo" />
        <item
            android:id="@+id/nav_corinthians"
            android:icon="@drawable/ic_launcher_foreground"
            android:title="@string/corinthians" />
        <item
            android:id="@+id/nav_goias"
            android:icon="@drawable/ic_launcher_foreground"
            android:title="@string/goias" />
    </menu>
  • nav_header.xml (pasta layout)

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="16dp"
        android:background="@color/green">
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_launcher_background" />
        <TextView
            android:id="@+id/header_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Times de Futebol"
            android:textColor="@color/white"
            android:textSize="20sp"
            android:textStyle="bold" />
        <TextView
            android:id="@+id/header_subtitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Escolha seu time"
            android:textColor="@color/white"
            android:textSize="16sp" />
    </LinearLayout>
  • fragment_corinthians.xml

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="16dp">
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_launcher_foreground" />
        <TextView
            android:id="@+id/text_corinthians"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Corinthians"
            android:textSize="20sp" />
    </LinearLayout>
  • fragment_flamengo.xml

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="16dp">
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_launcher_foreground" />
        <TextView
            android:id="@+id/text_corinthians"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Flamengo"
            android:textSize="20sp" />
    </LinearLayout>
  • fragment_goias.xml

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="16dp">
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_launcher_foreground" />
        <TextView
            android:id="@+id/text_goias"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Goiás"
            android:textSize="20sp" />
    </LinearLayout>
  • nav_header.xml (pasta layout)

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="16dp"
        android:background="@color/green">
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_launcher_background" />
        <TextView
            android:id="@+id/header_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Times de Futebol"
            android:textColor="@color/white"
            android:textSize="20sp"
            android:textStyle="bold" />
        <TextView
            android:id="@+id/header_subtitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Escolha seu time"
            android:textColor="@color/white"
            android:textSize="16sp" />
    </LinearLayout>
  • CorinthiansFragment.java

    import android.os.Bundle;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import androidx.fragment.app.Fragment;
    public class CorinthiansFragment extends Fragment {
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            return inflater.inflate(R.layout.fragment_corinthians, container, false);
        }
    }
  • FlamengoFragment.java

    import android.os.Bundle;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import androidx.fragment.app.Fragment;
    public class FlamengoFragment extends Fragment {
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            return inflater.inflate(R.layout.fragment_flamengo, container, false);
        }
    }
  • GoiasFragment.java

    import android.os.Bundle;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import androidx.fragment.app.Fragment;
    public class GoiasFragment extends Fragment {
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            return inflater.inflate(R.layout.fragment_goias, container, false);
        }
    }

MainActivity.java

import android.os.Bundle;
import android.view.MenuItem;
import androidx.activity.OnBackPressedCallback;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import com.google.android.material.navigation.NavigationView;
public class MainActivity extends AppCompatActivity {
    private DrawerLayout drawerLayout;
    private NavigationView navigationView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        drawerLayout = findViewById(R.id.drawer_layout);
        navigationView = findViewById(R.id.navigation_view);
        navigationView.setNavigationItemSelectedListener(item -> {
            Fragment selectedFragment = null;
            int id = item.getItemId();
            if (id == R.id.nav_flamengo) {
                selectedFragment = new FlamengoFragment();
            } else if (id == R.id.nav_corinthians) {
                selectedFragment = new CorinthiansFragment();
            } else if (id == R.id.nav_goias) {
                selectedFragment = new GoiasFragment();
            }
            if (selectedFragment != null) {
                getSupportFragmentManager()
                        .beginTransaction()
                        .replace(R.id.fragment_container, selectedFragment)
                        .commit();
            }
            drawerLayout.closeDrawer(GravityCompat.START);
            return true;
        });
        if (savedInstanceState == null) {
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.fragment_container, new FlamengoFragment())
                    .commit();
        }
        getOnBackPressedDispatcher().addCallback(this,
                new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
                if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
                    drawerLayout.closeDrawer(GravityCompat.START);
                } else {
                    // Fecha a Activity
                    finish();
                }
            }
        });
    }
}//class

Exemplo prático 2 (Elementos do Navigation Drawer):

No arquivo Gradle a nível de módulo, ative o DataBinding

  buildFeatures {
        viewBinding = true
    }

Na pasta layout adicione:

  • activty_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:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:openDrawer="start">
        <include
            android:id="@+id/app_bar_main"
            layout="@layout/app_bar_main"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
        <com.google.android.material.navigation.NavigationView
            android:id="@+id/nav_view"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:fitsSystemWindows="true"
            app:headerLayout="@layout/nav_header_main"
            app:menu="@menu/activity_main_drawer" />
    </androidx.drawerlayout.widget.DrawerLayout>
  • app_bar_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.coordinatorlayout.widget.CoordinatorLayout 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"
        tools:context=".MainActivity">
        <com.google.android.material.appbar.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/Theme.ExemploNavigationDrawer_01.AppBarOverlay">
            <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                app:popupTheme="@style/Theme.ExemploNavigationDrawer_01.PopupOverlay" />
        </com.google.android.material.appbar.AppBarLayout>
        <include layout="@layout/content_main" />
        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/fab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|end"
            android:layout_marginEnd="@dimen/fab_margin"
            android:layout_marginBottom="16dp"
            app:srcCompat="@android:drawable/ic_menu_agenda" />
    </androidx.coordinatorlayout.widget.CoordinatorLayout>
  • content_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout 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"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        tools:showIn="@layout/app_bar_main">
        <fragment
            android:id="@+id/nav_host_fragment_content_main"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:defaultNavHost="true"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:navGraph="@navigation/mobile_navigation" />
    </androidx.constraintlayout.widget.ConstraintLayout>
  • nav_header_main.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"
        android:layout_width="match_parent"
        android:layout_height="@dimen/nav_header_height"
        android:background="@drawable/side_nav_bar"
        android:gravity="bottom"
        android:orientation="vertical"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:theme="@style/ThemeOverlay.AppCompat.Dark">
        <ImageView
            android:id="@+id/imageView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:contentDescription="@string/nav_header_desc"
            android:paddingTop="@dimen/nav_header_vertical_spacing"
            app:srcCompat="@mipmap/ic_launcher_round" />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingTop="@dimen/nav_header_vertical_spacing"
            android:text="@string/nav_header_title"
            android:textAppearance="@style/TextAppearance.AppCompat.Body1" />
        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/nav_header_subtitle" />
    </LinearLayout>
  • na pasta drawable, crie o arquivo side_nav_bar.xml

    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle">
        <gradient
            android:angle="135"
            android:centerColor="@color/yellow_200"
            android:endColor="@color/yellow_500"
            android:startColor="@color/yellow_700"
            android:type="linear" />
    </shape>
  • fragment_cake.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=".ui.coffee.CoffeeFragment">
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:id="@+id/image_cake"
            android:src="@drawable/ic_launcher_foreground"/>
        <TextView
            android:id="@+id/text_cake"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:layout_marginEnd="8dp"
            android:textAlignment="center"
            android:textSize="20sp"
             />
    </LinearLayout>
  • fragment_coffee.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=".ui.coffee.CoffeeFragment">
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:id="@+id/image_coffee"
            android:src="@drawable/ic_launcher_foreground"/>
        <TextView
            android:id="@+id/text_coffee"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:layout_marginEnd="8dp"
            android:textAlignment="center"
            android:textSize="20sp"
            />
    </LinearLayout>

Na pasta menu adicione:

  • activity_main_drawer.xml

    <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        tools:showIn="navigation_view">
        <group android:checkableBehavior="single">
            <item
                android:id="@+id/nav_cake"
                android:icon="@drawable/coffee"
                android:title="@string/menu_cake" />
            <item
                android:id="@+id/nav_coffee"
                android:icon="@drawable/strawberry_cake"
                android:title="@string/menu_coffee" />
        </group>
    </menu>
  • main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">
        <item
            android:id="@+id/action_settings"
            android:orderInCategory="100"
            android:title="@string/action_settings"
            app:showAsAction="never" />
        <item
            android:id="@+id/action_contact"
            android:orderInCategory="100"
            android:title="@string/contact"
            app:showAsAction="never" />
    </menu>

Na paste navigation adicione:

  • mobile_navigation.xml

    <?xml version="1.0" encoding="utf-8"?>
    <navigation 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:id="@+id/mobile_navigation"
        app:startDestination="@+id/nav_cake">
        <fragment
            android:id="@+id/nav_cake"
            android:name="com.example.exemplonavigationdrawer_01.ui.cake.CakeFragment"
            android:label="@string/menu_cake"
            tools:layout="@layout/fragment_cake" />
        <fragment
            android:id="@+id/nav_coffee"
            android:name="com.example.exemplonavigationdrawer_01.ui.coffee.CoffeeFragment"
            android:label="@string/menu_coffee"
            tools:layout="@layout/fragment_coffee" />
    </navigation>

Outros arquivos a serem adicionados no projeto:

  • colors.xml

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <color name="yellow_200">#FFEB3B</color>
        <color name="yellow_500">#FFC107</color>
        <color name="yellow_700">#FF9800</color>
        <color name="teal_200">#FF03DAC5</color>
        <color name="teal_700">#FF018786</color>
        <color name="black">#FF000000</color>
        <color name="white">#FFFFFFFF</color>
    </resources>
  • strings.xml

    <resources>
        <string name="app_name">ExemploNavigationDrawer_01</string>
        <string name="navigation_drawer_open">Open navigation drawer</string>
        <string name="navigation_drawer_close">Close navigation drawer</string>
        <string name="nav_header_title">Android Studio</string>
        <string name="nav_header_subtitle">android.studio@android.com</string>
        <string name="nav_header_desc">Navigation header</string>
        <string name="action_settings">Settings</string>
        <string name="menu_cake">Cake</string>
        <string name="menu_coffee">Coffee</string>
        <string name="contact">Contact</string>
    </resources>
  • dimens.xml

    <resources>
        <!-- Default screen margins, per the Android Design guidelines. -->
        <dimen name="activity_horizontal_margin">16dp</dimen>
        <dimen name="activity_vertical_margin">16dp</dimen>
        <dimen name="nav_header_vertical_spacing">8dp</dimen>
        <dimen name="nav_header_height">176dp</dimen>
        <dimen name="fab_margin">16dp</dimen>
    </resources>
  • MainActivity.java

    import android.os.Bundle;
    import android.util.Log;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.Menu;
    import android.widget.Toast;
    import com.google.android.material.snackbar.Snackbar;
    import com.google.android.material.navigation.NavigationView;
    import androidx.annotation.NonNull;
    import androidx.navigation.NavController;
    import androidx.navigation.Navigation;
    import androidx.navigation.ui.AppBarConfiguration;
    import androidx.navigation.ui.NavigationUI;
    import androidx.drawerlayout.widget.DrawerLayout;
    import androidx.appcompat.app.AppCompatActivity;
    import com.example.exemplonavigationdrawer_01.databinding.ActivityMainBinding;
    public class MainActivity extends AppCompatActivity {
        private AppBarConfiguration mAppBarConfiguration;
        private ActivityMainBinding binding;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            Log.e("MainActivity","onCreate");
            binding = ActivityMainBinding.inflate(getLayoutInflater());
            setContentView(binding.getRoot());
            setSupportActionBar(binding.appBarMain.toolbar);
            binding.appBarMain.fab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                            .setAction("Action", null)
                            .setAnchorView(R.id.fab).show();
                }
            });
            DrawerLayout drawer = binding.drawerLayout;
            NavigationView navigationView = binding.navView;
            // Passing each menu ID as a set of Ids because each
            // menu should be considered as top level destinations.
            mAppBarConfiguration = new AppBarConfiguration.Builder(
                    R.id.nav_cake, R.id.nav_coffee)
                    .setOpenableLayout(drawer)
                    .build();
            navigationView.setItemIconTintList(null); //para os icones ficarem coloridos
            NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
            NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
            NavigationUI.setupWithNavController(navigationView, navController);
        }
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }
        @Override
        public boolean onOptionsItemSelected(@NonNull MenuItem item) {
            if(item.getItemId() == R.id.action_settings){
                Toast.makeText(getApplicationContext(),"Settings",
                        Toast.LENGTH_SHORT).show();
            }
            if(item.getItemId() == R.id.action_contact){
                Toast.makeText(getApplicationContext(),"Contact",
                        Toast.LENGTH_SHORT).show();
            }
            return super.onOptionsItemSelected(item);
        }
        @Override
        public boolean onSupportNavigateUp() {
            NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
            return NavigationUI.navigateUp(navController, mAppBarConfiguration)
                    || super.onSupportNavigateUp();
        }
    }
  • CakeFragment.java

    import android.os.Bundle;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ImageView;
    import android.widget.TextView;
    import androidx.annotation.NonNull;
    import androidx.annotation.Nullable;
    import androidx.fragment.app.Fragment;
    import androidx.lifecycle.ViewModelProvider;
    import com.example.exemplonavigationdrawer_01.databinding.FragmentCakeBinding;
    import com.example.exemplonavigationdrawer_01.ui.coffee.CoffeeViewModel;
    public class CakeFragment extends Fragment {
        private FragmentCakeBinding binding;
        public View onCreateView(@NonNull LayoutInflater inflater,
                                 ViewGroup container, Bundle savedInstanceState) {
            binding = FragmentCakeBinding.inflate(inflater, container, false);
            View root = binding.getRoot();
            Log.i("CakeFragment","onCreateView");
            return root;
        }
        @Override
        public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
            // super.onViewCreated(view, savedInstanceState);
            CakeViewModel cakeViewModel =
                    new ViewModelProvider(this).get(CakeViewModel.class);
            final TextView textView = binding.textCake;
            cakeViewModel.getText().observe(getViewLifecycleOwner(),
                    textView::setText);
            final ImageView imageView = binding.imageCake;
            cakeViewModel.getInteger().observe(getViewLifecycleOwner(),imageView::setImageResource);
            Log.i("CakeFragment","onViewCreated");
        }
        @Override
        public void onDestroyView() {
            super.onDestroyView();
            binding = null;
            Log.i("CakeFragment","onDestroyView");
        }
    }
  • CakeViewModel.java

    import android.util.Log;
    import androidx.lifecycle.LiveData;
    import androidx.lifecycle.MutableLiveData;
    import androidx.lifecycle.ViewModel;
    import com.example.exemplonavigationdrawer_01.R;
    public class CakeViewModel extends ViewModel {
        private final MutableLiveData<String> mText;
        private final MutableLiveData<Integer> mImage;
        public CakeViewModel() {
            mText = new MutableLiveData<>();
            mText.setValue("This is cake fragment");
            mImage = new MutableLiveData<>();
            mImage.setValue(R.drawable.strawberry_cake);
            Log.i("CakeViewModel","construtor");
        }
        public LiveData<String> getText() {
            return mText;
        }
        public LiveData<Integer> getInteger() {
            return mImage;
        }
    }
  • CoffeeFragment.java

    import android.os.Bundle;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ImageView;
    import android.widget.TextView;
    import androidx.annotation.NonNull;
    import androidx.annotation.Nullable;
    import androidx.fragment.app.Fragment;
    import androidx.lifecycle.ViewModelProvider;
    import com.example.exemplonavigationdrawer_01.databinding.FragmentCoffeeBinding;
    public class CoffeeFragment extends Fragment {
        private FragmentCoffeeBinding binding;
        public View onCreateView(@NonNull LayoutInflater inflater,
                                 ViewGroup container, Bundle savedInstanceState) {
            binding = FragmentCoffeeBinding.inflate(inflater, container, false);
            View root = binding.getRoot();
            Log.e("CoffeeFragment","onCreateView");
            return root;
        }
        @Override
        public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
           // super.onViewCreated(view, savedInstanceState);
            CoffeeViewModel coffeeViewModel =
                    new ViewModelProvider(this).get(CoffeeViewModel.class);
            final TextView textView = binding.textCoffee;
            coffeeViewModel.getText().observe(getViewLifecycleOwner(), textView::setText);
            final ImageView imageView = binding.imageCoffee;
            coffeeViewModel.getInteger().observe(getViewLifecycleOwner(),imageView::setImageResource);
            Log.e("CoffeeFragment","onViewCreated");
        }
        @Override
        public void onDestroyView() {
            super.onDestroyView();
            binding = null;
            Log.e("CoffeeFragment","onDestroyView");
        }
    }
  • CoffeeViewModel.java

    import android.util.Log;
    import androidx.lifecycle.LiveData;
    import androidx.lifecycle.MutableLiveData;
    import androidx.lifecycle.ViewModel;
    import com.example.exemplonavigationdrawer_01.R;
    public class CoffeeViewModel extends ViewModel {
        private final MutableLiveData<String> mText;
        private final MutableLiveData<Integer> mImage;
        public CoffeeViewModel() {
            mText = new MutableLiveData<>();
            mText.setValue("This is coffee fragment");
            mImage = new MutableLiveData<>();
            mImage.setValue(R.drawable.coffee);
            Log.i("CoffeeViewModel","construtor");
        }
        public LiveData<String> getText() {
            return mText;
        }
        public LiveData<Integer> getInteger() {
            return mImage;
        }
    }

Animação Usando Arquivos JSON

Já vimos nos tópicos anteriores que o arquivo JSON facilita a troca de dados entre aplicativos, mas seria possível aplicá-lo em outras situações? Por exemplo: em animações? Sim, atualmente o JSON é usado também para essa finalidade, um exemplo disto é a biblioteca Lottie que renderiza animações exportadas do software Adobe After Effects.

Para saber mais detalhes sobre a biblioteca, acesse o projeto disponível no GitHub no seguinte endereço: https://github.com/airbnb/lottie-android

Exemplos práticos:

  • Crie um projeto na IDE;

  • Escolha uma Activity vazia;

  • No arquivo build.gradle, adicione uma dependência: dependencies

{…​ implementation "com.airbnb.android:lottie:4.2.2" //obter a lib …​}

  • Clique com o botão direito do mouse na pasta res e adicione um diretório chamado raw. Coloque o arquivo json baixado neste diretório.

  • No arquivo activity_main.xml, acrescente a tag:

    <com.airbnb.lottie.LottieAnimationView
       android:id="@+id/animation_view"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       app:lottie_rawRes="@raw/cube"    //onde fica o arquivo json
       app:lottie_autoPlay="true"   //iniciar a animação
       app:lottie_loop="true"   //animação continua indefinidamente
       />
  • Pronto, basta executar o app.

Referências do exemplo acima: