Headertab

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Friday 6 July 2018

Jetpack Navigation

Hello guys today we are learn about how to manage fragment navigation with jetpack library but before learn about navigation first you learn about What is Jetpack library?.


JetPack:
Android JetPack is a set of android components designed with Kotlin in mind, available with Android Studio 3.2.


Google’s annual I/O developer conference is where the company unveils their latest tools and features for Android developers, and this year is no exception. Today, the company announced Android Jetpack, a set of components to accelerate app development. Jetpack is designed with Kotlin in mind to help you simplify your code. The latest Android Studio 3.2 canary available today also features new tools for Jetpack.

Accelerating app development with Android JetPack

Android Jetpack is a set of Android components, tools, and guidance inspired by the backward compatibility of the Support Library and the ease of use of the Android Architecture Components. Jetpack components can broadly be categorized into four categories: Architecture, UI, Foundation, and Behavior.
Architecture components include activities like lifecycle management, ViewModel, data binding, and more. UI components include animation and transitions, fragments, layouts, and more. Foundation components include AppCompat, Multidex, testing, and more. Behavior components include media and playback, permissions, notifications, sharing and more.





WorkManager

This library provides an API for constraint-based background jobs that must be executed, replacing the need for jobs or SyncAdapters. It works on devices without Google Play Services, can create graphs of work, and can query the state of your work.

Navigation

Many applications are composed of multiple activities, but sharing data between activities and implementing transitions has been a pain-point for in-app navigation. The Navigation component will help you structure your in-app user interface as a single-Activity app. It supports Fragments out of the box so all the benefits of Architecture Components such as Lifecycle and ViewModel are there while the Navigation component handles FragmentTransitions for you. Furthermore, you can declare transitions that Navigation will automatically handle, you can build with the correct Up and Back behavior automatically, you can easily provide full support for deep links, and you can connect Navigation to UI widgets like the navigation drawer and bottom navigation. Lastly, the Navigation Editor in the latest Android Studio allows you to visually manage navigation properties

Paging

The Paging component, when combined with RecyclerView, allows you to add fast, infinite scrolling to your app. The idea is that the component simplifies managing data in pages, ie. pulling chunks of data in succession as quickly as possible and returning results for the user to view.

Slices

Lastly, the Slices component will simplify the process of implementing the Slices API introduced with Android P. It’s an API that lets you surface your app’s UI inside of the Google App as a search result.

Now you create a sample project and follow  below instructions :
If you had create new project then add these two line dependency and two line top of gradle in app level gradle like..

apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'androidx.navigation.safeargs'
implementation 'android.arch.navigation:navigation-fragment-ktx:1.0.0-alpha02'
implementation 'android.arch.navigation:navigation-ui-ktx:1.0.0-alpha02'

Complete gradle file like :
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'androidx.navigation.safeargs'
android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.samset.jetpacknavigation"
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.0.0-alpha1'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.0'
    implementation 'android.arch.navigation:navigation-fragment-ktx:1.0.0-alpha02'
    implementation 'android.arch.navigation:navigation-ui-ktx:1.0.0-alpha02'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0-alpha1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.0-alpha3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha3'
}
and project level gradle look like this 
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    ext.kotlin_version = '1.2.50'
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.0-alpha18'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'android.arch.navigation:navigation-safe-args-gradle-plugin:1.0.0-alpha02'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
allprojects {
    repositories {
        google()
        jcenter()
    }
}
task clean(type: Delete) {
    delete rootProject.buildDir
}
and now open open gradle.properties file and paste these two line

android.enableJetifier=trueandroid.useAndroidX=true

And now you create navigation xml
First you right click on res folder and create new resource file and now select resource type is "Navigation" and enter file name navigation_graph and press OK


Create tow or three fragment and follow some instructions

FragmentOne.kt

class FragmentOne : Fragment() {
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_fragment_one, container, false)
    }
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        /*
        * here i am navigate(transaction fragment first to second)
        * fragment with direction function you can choose another function
        * you can see second fragment tranction i am use another funtions for the transaction
        *
        * */
        btnNext1.setOnClickListener{
            var directions=FragmentOneDirections.action_fragmentSecond()
            // if you send data in bundle you can pass directly here
            directions.setMydata("Hello I am passed data from fragment one")
            var  controller=it.findNavController()
            controller.navigate(directions)
        }
    }
}

In FragmentOne i am use simple fragment transaction and you can pass data.

FragmentSecond.kt

class FragmentSecvond : Fragment() {
    internal var infos = User()
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_fragment_secvond, container, false)
    }
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        arguments?.let {
            var values=FragmentSecvondArgs.fromBundle(it)
            tvnames.text=values.mydata
        }
        /*
        * here i am set custom data in bundle with seralizable
        * */
        btnNext2.setOnClickListener{
            infos.username=" i am samset"
            infos.mobilenumber="98110540xxx"
            val bundle = Bundle()
            bundle.putSerializable("data",infos)
            val navController = it.findNavController()
            navController.navigate(R.id.fragmentThird,bundle)
        }
    }
}

In secondfragment you can see how to pass custom serialisable data to thirdfragment.


NOTE:-
If you want Maintain fragment backstack then override this method in your MainActivity

override fun onSupportNavigateUp()=findNavController(R.id.mainNavigationFragment).navigateUp()


If you want  not maintain the backstack specific fragment then you add one line of code in navigation_graph like..

<fragment
    android:id="@+id/fragmentSecvond"
    android:name="com.samset.jetpacknavigation.fragments.FragmentSecond"
    android:label="fragment_fragment_secvond"
    tools:layout="@layout/fragment_fragment_secvond">
    <argument
        android:name="mydata"
        android:defaultValue="defaulttext"
        app:type="string" />
    <action
        android:id="@+id/action_fragmentSecvond_to_fragmentThird"
        app:clearTask="true"   // add this line for clear backstack
        app:destination="@id/fragmentThird" />

</fragment>

You can also be change the action "Pop To" behavior from attribute pannel( from xml app:popUpTo="@+id/FragmentOne). This way when user will click back, he will be navigated to FragmentOne instead of the original destination.

<fragment
    android:id="@+id/fragmentThird"
    android:name="com.samset.jetpacknavigation.fragments.FragmentThird"
    android:label="fragment_fragment_third"
    tools:layout="@layout/fragment_fragment_third">
    <action
        android:id="@+id/action_fragmentThird_to_fragmentFourth"
        app:destination="@id/fragmentFourth" />
    <action
        app:popUpTo="@id/action_fragmentSecond" // add this line and change pop to destination
        android:id="@+id/action_fragmentThird_to_fragmentOne"
        app:destination="@id/fragmentOne" />

</fragment>


Thank you

Full SourceCode JetPack-Navigation




No comments:

Post a Comment