Home Blog Page 50

Flutter Sliver App Bar – An Collapsing ScrollView App Bar

0
Flutter Sliver App Bar Example
Flutter Sliver App Bar Example

Hi Guys, Welcome to Proto Coders Point , In This Tutorial we gonna implement A Sliver App Bar in Flutter App.

What is Sliver AppBar Class?

A Sliver AppBar in Flutter is similar to any normal AppBar, The Different here is only that Sliver AppBar come with ScrollView effect.

The Sliver App bar should be the first child of a CustomScrollView, Using with we can integrate the appbar with a scroll view so that it can vary in height and other content of the scrollview.

Implementation with Sliver AppBar Widget

Below Examples will show you how appbars can we integrated with different configurations and act with different behaviour when any user Scrolls the View up or down.

Example 1:

When App bar with

  1. floating: false,
  2. pinned: false,
  3. snap: false
Sliver App bar flutter
Example 1

StateFull Class Code

class _NewPageState extends State<NewPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        slivers: <Widget>[
          SliverAppBar(
            expandedHeight: 150.0,
            floating: false,
            pinned: false,
            snap: false,
            actions: <Widget>[
              IconButton(
                icon: const Icon(Icons.add_circle),
                onPressed: () {},
              ),
            ],
            flexibleSpace: FlexibleSpaceBar(
              title: Text(
                "Sliver App Bar Example",
                style: TextStyle(fontSize: 15),
              ),
              background: Image.asset(
                'images/images.jpeg',
                fit: BoxFit.cover,
              ),
            ),
          ),
          SliverFillRemaining(
            child: new Center(
              child: new Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Image.asset('images/protocoderspointlogo.png'),
                  SizedBox(
                    height: 20.0,
                  ),
                  Text(
                    "This is an Simple Sliver App Bar Flutter Example",
                    style:
                        TextStyle(fontSize: 15.0, fontWeight: FontWeight.w800),
                  ),
                ],
              ),
            ),
          )
        ],
      ),
    );
  }
}

 

Example 2 :

When Sliver App bar with

  1. floating: true,
  2. pinned: true,
  3. snap: false

sliver app bar example 2 scrollview

 

The Code base for this to work is very simply in the above lined of code you just need to change floating to true and pinned to true,  this Configuration will simple pin the app bar at the top of the screen when used scroll through the app and  other remaining widget will simple scroll to the end.

StateFull Class Code

class _NewPageState extends State<NewPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        slivers: <Widget>[
          SliverAppBar(
            expandedHeight: 150.0,
            floating: true, //change is here 
            pinned: true, //change si
            snap: true,
            actions: <Widget>[
              IconButton(
                icon: const Icon(Icons.add_circle),
                onPressed: () {},
              ),
            ],
            flexibleSpace: FlexibleSpaceBar(
              title: Text(
                "Sliver App Bar Example",
                style: TextStyle(fontSize: 15),
              ),
              background: Image.asset(
                'images/images.jpeg',
                fit: BoxFit.cover,
              ),
            ),
          ),
          SliverFillRemaining(
            child: new Center(
              child: new Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Image.asset('images/protocoderspointlogo.png'),
                  SizedBox(
                    height: 20.0,
                  ),
                  Text(
                    "This is an Simple Sliver App Bar Flutter Example",
                    style:
                        TextStyle(fontSize: 15.0, fontWeight: FontWeight.w800),
                  ),
                ],
              ),
            ),
          )
        ],
      ),
    );
  }
}

Explaination of above code

1. As i said before that Sliver App bar must be the child of CustomScrollView to get Scrolling effect, The CustomScrollView will make  the SliverAppBar into Scrolling.

2. Here i have Used an IconButton just to Show that you can even add IconButton Widget into the Appbar. i’e IconButton, which is used with actions to show buttons on the app bar.

Snippet

actions: <Widget>[
              IconButton(
                icon: const Icon(Icons.add_circle),
                onPressed: () {},
              ),
            ],

Flexible SpaceBar  is used so that we can easily set and maximum expandable size to it when user scroll the app Down-words,

And Even we can set many other properties like background,title etc

SliverFillRemaining that fills the remaining space in the viewport. In Other words The Remaining  body should not be null, is the Remaininig body is null then the app bar scrollview will not work as accepted, this value cannot be null.

So i have just Defined some widget in the remaining part in Sliver Fill Remaining

which has a child which is set to center , in turn has a child Column, then This Column have 3 children widget Image,SixedBox,and a Text.

Snippet Code

SliverFillRemaining(
            child: new Center(
              child: new Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Image.asset('images/protocoderspointlogo.png'),
                  SizedBox(
                    height: 20.0,
                  ),
                  Text(
                    "This is an Simple Sliver App Bar Flutter Example",
                    style:
                        TextStyle(fontSize: 15.0, fontWeight: FontWeight.w800),
                  ),
                ],
              ),
            ),
          )

 

Complete Source code of Flutter Sliver App Bar – An Collapsing ScrollView App Bar 

main.dart

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: NewPage(),
    );
  }
}

class NewPage extends StatefulWidget {
  @override
  _NewPageState createState() => _NewPageState();
}

class _NewPageState extends State<NewPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        slivers: <Widget>[
          SliverAppBar(
            expandedHeight: 150.0,
            floating: true,
            pinned: true,
            snap: true,
            actions: <Widget>[
              IconButton(
                icon: const Icon(Icons.add_circle),
                onPressed: () {},
              ),
            ],
            flexibleSpace: FlexibleSpaceBar(
              title: Text(
                "Sliver App Bar Example",
                style: TextStyle(fontSize: 15),
              ),
              background: Image.asset(
                'images/images.jpeg',
                fit: BoxFit.cover,
              ),
            ),
          ),
          SliverFillRemaining(
            child: new Center(
              child: new Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Image.asset('images/protocoderspointlogo.png'),
                  SizedBox(
                    height: 20.0,
                  ),
                  Text(
                    "This is an Simple Sliver App Bar Flutter Example",
                    style:
                        TextStyle(fontSize: 15.0, fontWeight: FontWeight.w800),
                  ),
                ],
              ),
            ),
          )
        ],
      ),
    );
  }
}

 

Flutter Circular Progress Indicator – Modal Progress HUD Flutter Library

5
Flutter Circular Progress Indicator

Hi  Guys, Welcome to Proto Coders Point , In this Tutorial is all about a flutter Widget Library known as Modal Progress HUD, By the use of this library we can show a Circular Progress Indicator in our flutter Applications.

Demo on Progress Indicator

Flutter Circular Progress Indicator

Modal Progress hud

In flutter progress indicator is an simple widget that is been wrap into other flutter widgets to enable modal progress indicator.

Here HUD stands for Heads Up Display.

let’s go straight into implementation of Flutter Circular Progress Indicator

Installation of Modal Progress HUD in our Flutter Project

To user this Package as a library

You need to add the required package’s dependencies into pubspec.yaml file

progress modal hud dependencies
progress modal hud dependencies
dependencies: 
  modal_progress_hud: ^0.1.3

Then, just click on Package Get

The above library of flutter circular progress indicator dependencies library version may update so to get latest version visit official site here.

Now you can use them by importing wherever required.

Importing the flutter progress indicator package wherever required

Now in your Dart code (main.dart), you can use:

import 'package:modal_progress_hud/modal_progress_hud.dart';

After importing the library in the required flutter page (main.dart)

Now, all you have to do is simply wrap your widget as a child of ModalProgressHUD, typically a form, together with a boolean that is maintained in local state.

Snippet Example Code

class _MyHomePage2State extends State<MyHomePage2> {
   bool show=false;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Progress Indicator Example"),
      ),
      body: ModalProgressHUD(
        inAsyncCall: show, // here show is bool value, which is used to when to show the progess indicator
        child: Column(
          children: <Widget>[
            Text(" Modal Progress Indicator ")
          ],
        ),
      ),
    );
  }
}

inAsyncCall : Accepts boolean type value, by setting this to true we can show the progress indicator in our flutter application.

The current parameters are customizable in the constructor

ModalProgressHUD(
  @required inAsyncCall: bool,
  @required child: Widget,
  opacity: double,
  color: Color,
  progressIndicator: CircularProgressIndicator,
  offset: double
  dismissible: bool,
);

Flutter Circular Progress Indicator  example with Source Code

main.dart

Copy Paste the below code in main.dart file to make it work.

import 'package:flutter/material.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool showProgressloading = false; // set to false
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Modal Progress HUD Example"),
      ),
      body: ModalProgressHUD(
        inAsyncCall: showProgressloading, // is set to false, so then login button is pressed it gets activated.
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 24.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
              Center(
                child: Text(
                  "Log-In",
                  style: TextStyle(
                      fontSize: 25,
                      fontStyle: FontStyle.italic,
                      fontWeight: FontWeight.w800),
                ),
              ),
              SizedBox(
                height: 48.0,
              ),
              TextField(
                keyboardType: TextInputType.emailAddress,
                showCursor: true,
                decoration: InputDecoration(hintText: "Enter your Email"),
                onChanged: (value) {},
              ),
              SizedBox(
                height: 15.0,
              ),
              TextField(
                obscureText: true,
                showCursor: true,
                decoration: InputDecoration(hintText: "Enter your password"),
                onChanged: (value) {},
              ),
              SizedBox(
                height: 15.0,
              ),
              MaterialButton(
                elevation: 5.0,
                color: Colors.blueAccent,
                child: Text(
                  "Log-In",
                  style: TextStyle(color: Colors.white),
                ),
                onPressed: () {
                  print("Button Clicked");

                  setState(() {
                    showProgressloading = true; // then login button is pressed the circular flutter indicator will get active
                  });
                  // stop the Progress indicator after 5 seconds
                  new Future.delayed(const Duration(seconds: 5), () {
                    setState(() => showProgressloading = false);
                  });
                },
              )
            ],
          ),
        ),
      ),
    );
  }
}

So the Source code will show a simple Login screen.

It have 2 TextField and a Button.

When the user press the login button the Flutter Circular progress indicator will be show.

  1. On initial load, showProgressloading is false which causes your child widget to display
  2. When Login button is pressed, showProgressloading is set to true, and will display the modal progress.
  3. Then once Futur Delayed is Completed,showProgressloading is set back to false, This will hide the progress Indicator.

and here i m making user of Future.delayed to show the progress indicator for 5 seconds.

you can just copy paste the above lines of code into your project.

30 Best Quotes on Programming – Software Development Quotes

0
Quotes on Programming
Quotes on Programming

Hi Guys, Welcome to Proto Coders Point, In blog post is all about Software Development Quotes.

In this Post i will be sharing 30 best programming quotes that i have found from the web and this motivational quotes for programmers has motivated me to become a successful programmer in my career.

This Quotes on Programming are very much inspiring so i think this motivational Coding quotes/software quotes will motivate other programmers to build their own Career Goals.

And Hence i thought to share this programming quotes & sayings with you.

NOTE: Developer Quotes or programmers sayings in this post are none of mine quotes and please forgive me if i have missed to mention the right source.

30 Best programming quotes – Software Development Quotes

1. Don’t worry if it doesn’t work right.If everything did, you’d be out of a job.

2. Don’t comment bad code – rewrite it. – Brian Kernighan

Quotes on programming

3. A programming language is for thinking about programs, not for expressing programs you’ve already thought of. It should be a pencil, not a pen. – Paul Graham

4. Debugging is twice as hard as writing the code in the first place.Therfore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. – Rajanand

5. The computer was born to solve problems that did not exist before. – Bill Gates

Developer Quotes

6. We have to stop optimizing for programmers and start optimizing for users. — Jeff Atwood

7. All computers wait at the same speed.

8. Artificial Intelligence usually beats natural stupidity.
Artificial Intelligence quotes
 
9. Don’t compare yourself with anyone in this world…if you do so, you are insulting yourself. – Bill Gates
 
10. If you are born poor it’s not your mistake, but if you die poor it’s your mistake. – Bill Gates Quotes
 

11. Any fool can use a computer. Many do. –Ted Nelson

12. First, solve the problem. Then, write the code. – John Johnson

programming quotes and sayings

 13. Experience is the name everyone gives to their mistakes. – Oscar Wilde

14. “Programs must be written for people to read, and only incidentally for machines to execute.” – Harold Abelson

15. “Any fool can write code that a computer can understand. Good programmers write code that humans can understand.” – Martin Fowler

16. “I’m not a great programmer; I’m just a good programmer with great habits.” – Kent Beck

coding quotes

17. “How you look at it is pretty much how you’ll see it” – Rasheed Ogunlaru

18. “Computers are useless.  They can only give you answers.” –  Pablo Picasso

19. “The question of whether computers can think is like the question of whether submarines can swim.”

20. “Never trust a computer you can’t throw out a window.”

21. “ It’s hard enough to find an error in your code when you’re looking for it; it’s even harder when you’ve assumed your code is error-free. ”  – Steve McConnell

22.  “Walking on water and developing software from a specification are easy if both are frozen. ” – Edward V Berard

23. “Programming isn’t about what you know; it’s about what you can figure out.” – Chris Pine

24. “The only way to learn a new programming language is by writing programs in it.” – Dennis Ritchie

25. “Sometimes it’s better to leave something alone, to pause, and that’s very true of programming.” – Joyce Wheeler

26. “The most damaging phrase in the programming language is.. it’s always been done this way” – Grace Hopper

27. “Most good programmers do programming not because they expect to get paid or get adulation by the public, but because it is fun to program” – Linus Torvalds

28. “Intelligence is the ability to avoid doing work, yet getting the work done” – Linus Torvalds

29. “Before you start some work, always ask yourself three questions –

  1. Why am I doing it,
  2. What the results might be and
  3. Will I be successful.
chanakya quotes
chanakya quotes

Only when you think deeply and find satisfactory answers to these questions, go ahead.” – Chanakya

30. Nothing will work unless you do. – Maya Angelou

About Proto Coders Point

We most write programming contents that are related to Mobile Application Development.

the First category is Android and The other one is Cross Platform i.e Flutter Application Development for android, iOS as well as Web development

Shimmer Effect Android – A Facebook Github – Display loading indicator

0
Shimmer Effect Android Display loading indicator
Shimmer Effect Android Display loading indicator

Hi Guys, Welcome to Proto Coders Point, In this Android Github library tutorial we will discuss and implement Facebook Shimmer Effect library which is easy to implement, and a flexible way to add a shimmering effect to any view in an Android app.

What is Shimmer Effect?

A Shimmer Effect is just an shine effect on any of the View like text, images or any widget.

Shimmer is one of the Android github library that is one of the easiest way to add an shimmer effect to a views in android xml layout.

Now a day it is mostly used as loading indicator.

Facebook shimmer android effect is been implemented in the layout file, That means we can simple nest any number of android views inside a ShimmerFrameLayout tag. and just you need to initialize and call the start or stop shimmer method to begin animation effect.

Ok let’s begin adding the Library in our android project

Final Result of the Below Complete Code

Facebook Shimmer Effect Android

youtube video Tutorial on Facebook Shimmer android example

 

Implementation of Facebook shimmer effect library

1. Adding dependencies in your project

To include Shimmer in your project, add the following dependency:

Project > App > Gradle Script > Open build.gradle(module.app)

// Gradle dependency on Shimmer for Android
dependencies {
  implementation 'com.facebook.shimmer:shimmer:0.5.0'
}

then after adding library just click on sync now  and now all set shimmer library is added in project successfully.

2. Xml Usage

Snippet code of ShimmerFrameLayout

<com.facebook.shimmer.ShimmerFrameLayout
     android:id="@+id/shimmer_view_container"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content">


     ...(your view here)...
</com.facebook.shimmer.ShimmerFrameLayout>

The above snippet code will show how you can use the Library view.

you can also initialize to auto_start to start the shimmer animation

there are many other attributes of this library

Attributes

You can control the look and pace of the effect using a number of custom attributes on the ShimmerFrameLayout tag.

Clip to Children
Whether to clip the shimmering effect to the children, or to opaquely draw the shimmer on top of the children. Use this if your overall layout contains transparency.
Colored
Whether you want the shimmer to affect just the alpha or draw colors on-top of the children.
Base Color
If colored is specified, the base color of the content.
Highlight Color
If colored is specified, the shimmer’s highlight color.
Base Alpha
If colored is not specified, the alpha used to render the base view i.e. the unhighlighted view over which the highlight is drawn.
Highlight Alpha
If colored is not specified, the alpha of the shimmer highlight.
Auto Start
Whether to automatically start the animation when the view is shown, or not.
Duration
Time it takes for the highlight to move from one end of the layout to the other.
Repeat Count
Number of times of the current animation will repeat.
Repeat Delay
Delay after which the current animation will repeat.
Repeat Mode
What the animation should do after reaching the end, either restart from the beginning or reverse back towards it.
Direction
The travel direction of the shimmer highlight: left to right, top to bottom, right to left or bottom to top.
Dropoff
Controls the size of the fading edge of the highlight.
Intensity
Controls the brightness of the highlight at the center
Shape
Shape of the highlight mask, either with a linear or a circular gradient.
Tilt
Angle at which the highlight is tilted, measured in degrees
Fixed Width, Height
Fixed sized highlight mask, if set, overrides the relative size value
Width, Height ratio
Size of the highlight mask, relative to the layout it is applied to.

For example

app:shimmer_auto_start="true"

3.  Programmatically start and stop of shimmer effect

create the object of Shimmer Frame Layout , i have create it as shimmer1, because i have 2 shimmer

ShimmerFrameLayout shimmer1;

point out to the reference view using shimmerFrameLayout id

shimmer1= (ShimmerFrameLayout) findViewById(R.id.shimmer_view_container1);

then, all you need to do is just call the startShimmer() method to start the animation effect.

shimmer1.startShimmer();

You can even stop the Shimmer effect using stop method

shimmer1.stopShimmer();

Complete Code of Facebook Shimmer Effect for android Application to show loading indication

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:background="#D6D6D6">
    <TextView
        android:id="@+id/textloading"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Loading Image.."
        android:layout_gravity="center"
        android:textSize="25sp"
        android:textStyle="bold|italic"/>
    <com.facebook.shimmer.ShimmerFrameLayout
        android:id="@+id/shimmer_view_container1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="5dp"
        >
    <View
        android:id="@+id/view1"
        android:layout_width="200dp"
        android:layout_height="300dp"
        android:background="#8A8888"
        android:layout_gravity="center"/>
    </com.facebook.shimmer.ShimmerFrameLayout>
    <ImageView
        android:layout_width="200dp"
        android:layout_height="300dp"
        android:visibility="gone"
        android:layout_gravity="center"
        android:id="@+id/imageload"
        android:background="@drawable/imageloaded"/>

    <com.facebook.shimmer.ShimmerFrameLayout
        android:id="@+id/shimmer_view_container2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:shimmer_shape="radial"
        android:layout_gravity="center">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="PROTO CODERS POINT"
            android:layout_gravity="center"
            android:textSize="25sp"
            android:textStyle="bold|italic"/>
    </com.facebook.shimmer.ShimmerFrameLayout>

    <TextView
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Demo of Facebook Shimmer Effect"/>
</LinearLayout>

Main_Activity.java

package com.ui.shimmereffect;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.facebook.shimmer.ShimmerFrameLayout;

public class MainActivity extends AppCompatActivity {

    ShimmerFrameLayout shimmer1,shimmer2;
    ImageView imageload;
    View view1;
    TextView loading;

    Handler handler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        handler= new Handler();

        imageload=(ImageView)findViewById(R.id.imageload);
        view1=(View)findViewById(R.id.view1);
        loading=(TextView)findViewById(R.id.textloading);

        shimmer1= (ShimmerFrameLayout) findViewById(R.id.shimmer_view_container1);
       shimmer1.startShimmer(); //start Shimmer animation of shimmer 1


        shimmer2= (ShimmerFrameLayout) findViewById(R.id.shimmer_view_container2);
        shimmer2.startShimmer(); //start Shimmer animation of shimmer 1

        Log.d("text","wait for 3 secs to load image");

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Log.d("text2","working");

                shimmer1.stopShimmer();
                view1.setVisibility(View.GONE);
                loading.setText("Loaded");

                imageload.setVisibility(View.VISIBLE);
            }
        },3000);

    }
}

Note: Here i am making use of handler to show the Facebook shimmer android effect for 3 seconds and then show the image.

you need to add an image in drawable folder to show image in ImageView.

Android ViewStub Tutorial With Example In Android Studio

0
Android ViewStub Tutorial With Example In Android Studio
Android ViewStub Tutorial With Example In Android Studio

Android ViewStub, is a called as zero sized invisible view with which you can use load “layout resource” at the runtime by saving lot’s of processing time, ViewStub in android is a Zero Dimension View.

In android viewStub a layout is refered by a ViewStub is been inflated and added to UI only then we decide, In other words, A view is been displayed when every it is in real use by making it just visible. or when inflate() method is invokeed.

The Layout resource is inflated and then viewstub get replaces in its parent. The ViewStub is been displayed/ exists in the UI unitl the setVisibility is VISIBLE or inflate is invoked.

The android ViewStub is used when any Layout view are rarely used, this can reduce the memory usage and thus this will speed up the rendering of the views

DEMO ON VIEWSTUB ANDROID

Android ViewStub Tutorial With Example In Android Studio
Android ViewStub Tutorial With Example In Android Studio

Basic Syntax of ViewStup XML:

<ViewStub
        android:id="@+id/ViewStubId"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:inflatedId="@+id/inflatedview"
        android:layout="@layout/activity_custum_view_stub" />

Then, the ViewStub can be defined that can be found using it’s id “ViewStubId”.

So after Inflation of the Layout ” activitity_custum_view_stub”. the view Stub is been removed from its parent.

Then the view which is been created by inflating the layout resource ” activitity_custum_view_stub” is found using the inflate is “inflateviewId”.

Important Methods Of ViewStub:

1. getInflatedId(): This method is used to get the id taken by the inflated view. This method returns an integer type value.

ViewStub simpleViewStub = new ViewStub(getApplicationContext()); // get the reference of ViewStub
int infaltedId = simpleViewStub.getInflatedId(); //using this we can get the id if the Inflated view

2. setLayoutResource(int layoutResource): This method is used to set the layout resource to inflate when this StubbedView becomes visible or invisible or when inflate() is invoked.

Below we set the layout resource that is used while inflating.

ViewStub simpleViewStub = new ViewStub(getApplicationContext()); // get the reference of ViewStub
simpleViewStub.setLayoutResource(R.layout.stub_layout); // set layout resource to inflate

3. inflate(): Ok now this inflate method is used to inflate the layout resource identified by getLayoutResource() and then replaces  it with our StubbedView in its parent.

View inflated = simpleViewStub.inflate();

4. setVisibility(int visibility): So the setVisibility method is used as it sounds i,e we can manually set the view to VISIBLE OR INVISIBLE OR GONE.

simpleViewStub.setVisibility(View.INVISIBLE);

5. setOnInflateListener(OnInflateListenerinflateListener): This method is used to listener event when we inflate the ViewStub. It specifies the inflate listener to be notified after this ViewStub successfully inflated its layout resource.

ViewStub simpleViewStub = new ViewStub(getApplicationContext()); // get the reference of ViewStub
// perform setOnInflateListener event
simpleViewStub.setOnInflateListener(new ViewStub.OnInflateListener() {
@Override
public void onInflate(ViewStub stub, View inflated) {
// do something here.
}
});

Android Viewstub example in Android Studio implementation:

Step 1 : Create a new Android Project

As usual now you need to create a new android project or just implement this viewStub in your existing project all left to you.

Step 2 : Design the UI

Open Open res -> layout ->activity_main.xml and  then just add below xml code:

activity_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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:background="#9C7777"
    android:elevation="50dp"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_marginTop="20dp"
        android:layout_gravity="center">

    <Button
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:text="Show"
        android:id="@+id/ButtonShow"/>
    <Button
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:text="Hide"
        android:id="@+id/ButtonHide"/>
    <ViewStub
        android:id="@+id/simpleViewStub"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:inflatedId="@+id/inflatedview"
        android:layout="@layout/activity_custum_view_stub" />
    </LinearLayout>

</LinearLayout>

Step 3 : Create a new XML File activity_custum_view_stub.xml

The copy paste the below xml code in the new xml file you just created.

<?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"
    tools:context=".CustumViewStub"
    android:orientation="vertical">
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        app:srcCompat="@drawable/images"
         />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="This is An Example for Android ViewStub"/>
</LinearLayout>

Step 4: Open   src -> package -> MainActivity.java

MainAcitivity.java

In this step Firstly we get the reference of Button’s and ViewStub and then inflate the layout resource. In this we perform click events on Show and Hide Button’s. Show Button is used to show the inflated view and hide button is used to hide the inflated view from the screen. In inflated view i.e custom_stub.xml we display a ImageView with a TextView.

package com.ui.viewstub;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.view.ViewStub;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    ViewStub ViewStub;
    Button showButton, hideButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ViewStub = ((ViewStub) findViewById(R.id.simpleViewStub));
        ViewStub.inflate();
        showButton = (Button) findViewById(R.id.ButtonShow); // get the reference of show button
        hideButton = (Button) findViewById(R.id.ButtonHide);

        showButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ViewStub.setVisibility(View.VISIBLE);
            }
        });

        hideButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ViewStub.setVisibility(View.GONE);
            }
        });
    }
}

Then, It’s all set the app is ready to run for testing.

Hero Animation in Flutter Application Development

1
flutter hero animations
flutter hero animations

Hi Guys, Welcome to Proto Coders Point, In this Tutorial Will be implement  Hero Animation in flutter using a Widget Called Hero.

Hero Animation in Flutter Application Development

Hero Transition is a great to show an animation effect in flutter. They let’s the user know that they have changed the screens, while keeping the focus of the interaction.

Flutter has a widget  called Hero,That will automatically create an hero animation transition effect between two navigation Routes.

Hero Animation in Flutter Application Development

Flutter will figure out the widget in both routes & animate the chnages that happens between the route locations.

Let’s suppose you have to show animation effect on a image in flutter app as your UI Hero Animation.

Put it on both the page screen routes.

The one that you’ll be transition from (MyHomePage.dart) and the one you’ll be transition to (Screen2.dart).

Then just you need to Wrap the Flutter Image Widget with a Here Widget on both the Pages.

snippet Code of Hero Animation Widget

Hero(
              tag: 'image',
              child: Container(
                child: Image.asset('images/flash.png'),
                height: 300.0,
              ),
),

then you need to provide a tag to you hero Animation widget.

the Important thing is to use the same tag on both the pages,So that Flutter gets to know which Hero we are Animating.

Video Tutorial

Implementation of Flutter Hero Animation Widget to show Transition Effect

I have created new Flutter project in Android Studio, and then Created a 2 screens i.e main.dart and Screen2.dart

Copy and paste the below codes in respective dart files.

main.dart

hero animation in flutter
import 'package:flutter/material.dart';
import 'package:flutter_app_hero_animation/screen2.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
      routes: {
        'screen2': (context) => Screen2(),
      },
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Hero Animation'),
      ),
      body: Column(
        children: <Widget>[
          RaisedButton(
            child: Text("Go to Screen 2"),
            onPressed: () {
              Navigator.pushNamed(context, 'screen2');
            },
          ),
          Hero(
            tag: 'image',
            child: Container(
              child: Image.asset('images/flash.png'),
              height: 100.0,
            ),
          ),
        ],
      ),
    );
  }
}

Here in main.dart file i have created a Named routes from that i can easily Navigate from main.dart to Screen2.dart.

main.dart file have 2 main widgets that is a RaisedButton and an Hero widget that contains child as Container with in turn has a child with Widget Image.

Screen2.dart

hero animation in flutter
hero animation screen 2
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Screen2(),
    );
  }
}

class Screen2 extends StatefulWidget {
  @override
  _Screen2State createState() => _Screen2State();
}

class _Screen2State extends State<Screen2> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Hero Animation'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'This is Screen 2',
              style: TextStyle(fontSize: 25.0),
            ),
            Hero(
              tag: 'image',
              child: Container(
                child: Image.asset('images/flash.png'),
                height: 300.0,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

as you can see in both the above pages codes that i have made user of Hero Widget that has a tag : ‘image’ with both the pages so that flutter can identify which widget should show Hero Animation

and All is set app is ready to show Hero Amination in your flutter app.

For Custom Animation in Flutter check out this post  here