Sunday, May 21, 2017

Android CollapsingToolbarLayout

May 21, 2017

Android CollapsingToolbarLayout is one of the most common features on android material design. By using collapsing toolbar we can now collapse our android app toolbar and use image or others things on the toolbar and that visibility is gone with collapse.

In this post, We will learn how to use Collapsing Tollbar layout.

Let's check documentation

Now start- First, add design dependence on your build.graddle file. (But it automatically added by the android studio. But lets a check)

dependencies {
    //some code
    compile 'com.android.support:design:23.0.1'
}

Now go to your XML file. In my case activity_main.xml it looks like-

<android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay"/>

    </android.support.design.widget.AppBarLayout>

Now we add collapsing toolbar layout in AppBarLayout. Let's add-

<android.support.design.widget.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/main_collapsing_tb"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            app:contentScrim="?attr/colorPrimary">

here we use scroll flag for how our layout should be scrolled. we want to scroll and exit until collapsed. now modify Toolbar. just adding a line.

app:layout_collapseMode="pin"

Now our collapsing toolbar is working. We here use only a toolbar in collapsing toolbar layout. But you can add picture and others things. If you are adding picture the modify code

app:layout_collapseMode="parallax"

Ok. That's it. If you miss some code or don't understand code where to use then see below full code.

<android.support.design.widget.AppBarLayout
        android:layout_height="@dimen/main_app_bar"
        android:layout_width="wrap_content"
        android:fitsSystemWindows="true"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.design.widget.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/main_collapsing_tb"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            app:contentScrim="?attr/colorPrimary">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                android:layout_gravity="top"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/AppTheme.PopupOverlay" />

        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>
Thanks for reading this post.
Hope you are able to use this feature.



 Happy coding

Read More

Thursday, May 18, 2017

Android RecycleView and OnClickListener part 2

May 18, 2017

If you miss Part 1. Please Check Part 1 first by clicking here.

Now come back to your MainActivity.java follow some steps-
  • Create SubjectList type ArrayList
  • Create Adapter and initialize it
  • set adapter to RecyclerView by recyclerView.setAdapter(adapter);
  • at last, fill the array list.
See the code-
public class MainActivity extends AppCompatActivity {

    private ArrayList<SubjectList> arrayList;

    public static final String [] list = {
            "one", "two", "three",
            "four", "five", "six",
            "seven", "eight", "nine",
            "ten", "eleven", "twelve",
            "thirteen", "fourteen", "fifteen",
            "sixteen", "seventeen", "eighteen"

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        
        fillUpArray();
        
        //initialize adapter
        MainAdapter adapter = new MainAdapter(arrayList,this);

        recyclerView.setAdapter(adapter);

    }

    private void fillUpArray() {

        arrayList = new ArrayList<>();
        
        for (int i = list.length; i > 0 ; i--) {
            SubjectList sub = new SubjectList(list[(list.length)- i]);
            arrayList.add(sub);
        }

    }

}
That’s it. Now revise full code that we use here-

MainActivity.java

1:  package com.blogspot.shudiptotrafder.androidaio;  
2:    
3:  import android.content.Intent;  
4:  import android.os.Bundle;  
5:  import android.support.v7.app.AppCompatActivity;  
6:  import android.support.v7.widget.LinearLayoutManager;  
7:  import android.support.v7.widget.RecyclerView;  
8:  import android.util.Log;  
9:  import android.view.Menu;  
10:  import android.view.MenuItem;  
11:    
12:  import com.blogspot.shudiptotrafder.androidaio.main.MainAdapter;  
13:  import com.blogspot.shudiptotrafder.androidaio.main.SubjectList;  
14:    
15:  import java.util.ArrayList;  
16:    
17:  public class MainActivity extends AppCompatActivity {  
18:    
19:    private ArrayList<SubjectList> arrayList;  
20:    
21:    public static final String[] list = {  
22:        "one", "two", "three",  
23:        "four", "five", "six",  
24:        "seven", "eight", "nine",  
25:        "ten", "eleven", "twelve",  
26:        "thirteen", "fourteen", "fifteen",  
27:        "sixteen", "seventeen", "eighteen"  
28:    
29:    };  
30:    
31:    private static final String logTag = MainActivity.class.getSimpleName();  
32:    
33:    @Override  
34:    protected void onCreate(Bundle savedInstanceState) {  
35:      super.onCreate(savedInstanceState);  
36:      setContentView(R.layout.activity_main);  
37:    
38:      RecyclerView recyclerView = (RecyclerView) findViewById(R.id.main_recyView);  
39:    
40:      fillUpArray();  
41:    
42:      //initialize adapter  
43:      MainAdapter adapter = new MainAdapter(arrayList,this);  
44:    
45:      LinearLayoutManager linearLayoutManager = new  
46:          LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);  
47:    
48:      //setting layout manager  
49:      recyclerView.setLayoutManager(linearLayoutManager);  
50:      recyclerView.setNestedScrollingEnabled(false);  
51:      recyclerView.setAdapter(adapter);  
52:    
53:    }  
54:    
55:    private void fillUpArray() {  
56:    
57:      arrayList = new ArrayList<>();  
58:    
59:    
60:      for (int i = list.length; i > 0 ; i--) {  
61:        SubjectList sub = new SubjectList(list[(list.length)- i]);  
62:        arrayList.add(sub);  
63:        sl(String.valueOf(i));  
64:      }  
65:    
66:    }  
67:    
68:    private static void sl(String string){  
69:      if (BuildConfig.DEBUG){  
70:        Log.e(logTag,string);  
71:      }  
72:    }  
73:    
74:    //for option menu  
75:    @Override  
76:    public boolean onCreateOptionsMenu(Menu menu) {  
77:      // Inflate the menu; this adds items to the action bar if it is present.  
78:      getMenuInflater().inflate(R.menu.menu_main, menu);  
79:      return super.onCreateOptionsMenu(menu);  
80:    }  
81:    
82:    @Override  
83:    public boolean onOptionsItemSelected(MenuItem item) {  
84:    
85:      // Handle action bar item clicks here. The action bar will  
86:      // automatically handle clicks on the Home/Up button, so long  
87:      // as you specify a parent activity in AndroidManifest.xml.  
88:      int id = item.getItemId();  
89:    
90:      //noinspection SimplifiableIfStatement  
91:      if (id == R.id.action_settings) {  
92:        return true;  
93:      }  
94:    
95:      return super.onOptionsItemSelected(item);  
96:    }  
97:  }  
98:    

MainAdapter.java

1:  package com.blogspot.shudiptotrafder.androidaio.main;  
2:    
3:  import android.content.Context;  
4:  import android.content.Intent;  
5:  import android.support.v7.widget.RecyclerView;  
6:  import android.view.LayoutInflater;  
7:  import android.view.View;  
8:  import android.view.ViewGroup;  
9:  import android.widget.TextView;  
10:    
11:  import com.blogspot.shudiptotrafder.androidaio.LocationActivity;  
12:  import com.blogspot.shudiptotrafder.androidaio.R;  
13:  import com.blogspot.shudiptotrafder.androidaio.email.EmailValidationActivity;  
14:  import com.blogspot.shudiptotrafder.androidaio.fab.FabActivity;  
15:  import com.blogspot.shudiptotrafder.androidaio.string.StringFormatActivity;  
16:    
17:  import java.util.ArrayList;  
18:    
19:  /**  
20:   * AndroidAIO  
21:   * com.blogspot.shudiptotrafder.androidaio.main  
22:   * Created by Shudipto Trafder on 1/2/2017 at 10:22 PM.  
23:   * 
24:   */  
25:    
26:  public class MainAdapter extends RecyclerView.Adapter<MainAdapter.MainViewHolder> {  
27:    
28:    
29:    //Array list  
30:    private ArrayList<SubjectList> objects;  
31:    //context  
32:    private Context context;  
33:    
34:    //view holder class  
35:    class MainViewHolder extends RecyclerView.ViewHolder {  
36:    
37:      TextView textView;  
38:    
39:      private MainViewHolder(View itemView) {  
40:        super(itemView);  
41:        textView = (TextView) itemView.findViewById(R.id.main_card_tv);  
42:      }  
43:    }  
44:    
45:    //constructor  
46:    public MainAdapter(ArrayList<SubjectList> objects, Context context) {  
47:      this.objects = objects;  
48:      this.context = context;  
49:    }  
50:    
51:    @Override  
52:    public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {  
53:    
54:      View view = LayoutInflater.from(parent.getContext())  
55:          .inflate(R.layout.main_card_view,parent,false);  
56:      return new MainViewHolder(view);  
57:    }  
58:    
59:    @Override  
60:    public void onBindViewHolder(final MainViewHolder holder, int position) {  
61:    
62:      final SubjectList list = objects.get(position);  
63:    
64:      holder.textView.setText(list.getSubName());  
65:      holder.textView.setOnLongClickListener(new View.OnLongClickListener() {  
66:        @Override  
67:        public boolean onLongClick(View v) {  
68:          return false;  
69:        }  
70:      });  
71:    
72:      holder.textView.setOnClickListener(new View.OnClickListener() {  
73:        @Override  
74:        public void onClick(View v) {  
75:        context.startActivity(new Intent(context,EmailValidationActivity.class));  
76:        }  
77:      });  
78:    }  
79:    
80:    @Override  
81:    public int getItemCount() {  
82:      return objects.size();  
83:    }  
84:  }  
85:    
86:    

SubjectList

1:  package com.blogspot.shudiptotrafder.androidaio.main;  
2:    
3:  /**  
4:   * AndroidAIO  
5:   * com.blogspot.shudiptotrafder.androidaio.main  
6:   * Created by Shudipto Trafder on 1/3/2017 at 2:47 PM.  
7:   * 
8:   */  
9:    
10:  public class SubjectList {  
11:    
12:    private String subName;  
13:    
14:    public SubjectList(String subName) {  
15:      this.subName = subName;  
16:    }  
17:    
18:    public String getSubName() {  
19:      return subName;  
20:    }  
21:  }  
22:    

activity_main.xml

1:  <?xml version="1.0" encoding="utf-8"?>  
2:  <RelativeLayout  
3:    xmlns:android="http://schemas.android.com/apk/res/android"  
4:    xmlns:tools="http://schemas.android.com/tools"  
5:    android:id="@+id/activity_main"  
6:    android:layout_width="match_parent"  
7:    android:layout_height="match_parent"  
8:    android:paddingBottom="@dimen/activity_vertical_margin"  
9:    android:paddingLeft="@dimen/activity_horizontal_margin"  
10:    android:paddingRight="@dimen/activity_horizontal_margin"  
11:    android:paddingTop="@dimen/activity_vertical_margin"  
12:    tools:context="com.blogspot.shudiptotrafder.androidaio.MainActivity">  
13:    
14:    <android.support.v7.widget.RecyclerView  
15:      android:layout_width="match_parent"  
16:      android:layout_height="wrap_content"  
17:      android:layout_alignParentTop="true"  
18:      android:padding="10dp"  
19:      android:layout_alignParentStart="true"  
20:      android:id="@+id/main_recyView"/>  
21:    
22:  </RelativeLayout>  

main_card_view.xml

1:  <?xml version="1.0" encoding="utf-8"?>  
2:    
3:  <android.support.v7.widget.CardView  
4:    xmlns:android="http://schemas.android.com/apk/res/android"  
5:    android:layout_width="match_parent"  
6:    android:layout_height="wrap_content"  
7:    android:layout_marginTop="10dp"  
8:    android:elevation="10dp"  
9:    android:padding="10dp">  
10:    
11:    <TextView  
12:      android:id="@+id/main_card_tv"  
13:      android:layout_width="match_parent"  
14:      android:layout_height="wrap_content"  
15:      android:layout_gravity="center"  
16:      android:padding="10dp"  
17:      android:text="@string/app_name"  
18:      android:textSize="20sp"/>  
19:    
20:  </android.support.v7.widget.CardView>  
Now, this is the final picture of our RecyclerView with Simple List.
final picture rcv

Read More

Android RecycleView with OnClickListener

May 18, 2017

Android RecyclerView is more than flexible more than android  ListView. It is a container for rendering larger data set of views that can be recycled and scrolled very efficiently. RecyclerView is like traditional ListView, but with more flexibility to customizes and optimized to work with larger datasets.
Example of Android RecyclerView
recyclerView list main
recyclerView list
First, add the following android support library dependency to project build.graddle file.
dependencies {
    compile 'com.android.support:recyclerview-v7:25.0.1'
    compile 'com.android.support:cardview-v7:25.0.1'
} 

First, dependency for RecyclerView and Second is for CardView. We use cardView in Recyclerview row item layout file. now use below code to your layout file
<android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/main_recyView"/>

Now go to your java class file and use below code.

RecyclerView recyclerView = (RecyclerView) findViewById(R.id.main_recyView);

LinearLayoutManager linearLayoutManager = new 
LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);

//setting layout manager
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setNestedScrollingEnabled(false);

Here I use LinearLayoutManager and vertically scroll options. you can use another layout manager. Now create an Adapter of android RecyclerView. we also need ViewHolder Class. you can create this ViewHolder class in a separate class or in the child class of Adapter class. I create ViewHolder class in the Adapter class. in adapter class, we need two variables
  1. ArrayList
  2. Context
we also need android Recyclerview row item layout file. code is
<android.support.v7.widget.CardView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:elevation="10dp"
        android:padding="10dp">

        <TextView
            android:id="@+id/main_card_tv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:padding="10dp"
            android:text="@string/app_name"
            android:textSize="20sp"/>

    </android.support.v7.widget.CardView>
we also need Item type class. My class name is SubjectList.java you can change your choice. SubjectList.java code is
public class SubjectList {

        private String subName;

        public SubjectList(String subName) {
            this.subName = subName;
        }

        public String getSubName() {
            return subName;
        }
    }

Now adapter class
public class MainAdapter extends    RecyclerView.Adapter<MainAdapter.MainViewHolder> {


        //Array list
        private ArrayList<SubjectList> objects;
        //context
        private Context context;

        //view holder class
        class MainViewHolder extends RecyclerView.ViewHolder {

            TextView textView;

            private MainViewHolder(View itemView) {
                super(itemView);
                textView = (TextView) itemView.findViewById(R.id.main_card_tv);
            }
        }

        //constructor
        public MainAdapter(ArrayList<SubjectList> objects, Context context) {
            this.objects = objects;
            this.context = context;
        }

        @Override
        public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

            View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.main_card_view,parent,false);
            return new MainViewHolder(view);
        }

    @Override
    public void onBindViewHolder(final MainViewHolder holder, int position) {

        final SubjectList list = objects.get(position);

        holder.textView.setText(list.getSubName());

        holder.textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                context.startActivity(new Intent(context, LocationActivity.class));
                
            }
        });
    }

    @Override
    public int getItemCount() {
        return objects.size();
    }

}

RecyclerView OnclickListener

we add a listener in onBindViewHolder method. the code here-
@Override
        public void onBindViewHolder(final MainViewHolder holder, int position) {

            final SubjectList list = objects.get(position);
            
            holder.textView.setText(list.getSubName());

            holder.textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    context.startActivity(new Intent(context, LocationActivity.class));
                
            }
        });
            holder.textView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    return false;
            }
        });
    }
Note: If you have multiple views in Recyclerview row item layout file you can use Card view to setOnClickListener instead of Textview.

Code analysis

ViewHolder Class-
  • we make ViewHolder class extend of RecyclerView.ViewHolder
  • we have on TextView and we cast it.
that’s all of ViewHolder Class. Adapter class-
  • we initialize our two variables through constructor
  • in onCreateViewHolder methods we create a new view type that inflates a layout file through LayoutInflater and returns new ViewHolder class with a parameter with that’s view.
  • we create new SubjectList and initialize it through the position of the ArrayList item.
  • add set Text to View by getting getter method of SubjectList.
  • now setOnClickListener to the view
  • in final we just return the size of ArrayList in getItemCount() method.

Please check next Part. Next Part cover MainActivity code Revise of all code and final screenshot. Click here.

Read More

Android Floating Action Button with animation part-2

May 18, 2017

Welcome to the part two of our today's android project.
In the previous part, we create animation XML and drawable. Now we add fab code in the layout. (if you miss part one click here)

In my case my layout is activity_main.xml before doing this we need two colors in colors.xml.
Let's add this
<color name="fab1">#e2e21d</color>
<color name="fab2">#47e92e</color>
Now add three fab button. I share this code one by one.
<android.support.design.widget.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="150dp"
        android:layout_marginEnd="16dp"
        android:layout_gravity="bottom|end"
        android:elevation="6dp"
        android:src="@drawable/ic_person_outline_black_24dp"
        app:fabSize="normal"
        android:visibility="gone"
        android:id="@+id/fab_people"
        app:backgroundTint="@color/fab2"
        app:pressedTranslationZ="12dp"/>
next one
<android.support.design.widget.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="80dp"
        android:layout_marginEnd="16dp"
        android:layout_gravity="bottom|end"
        android:elevation="6dp"
        android:src="@drawable/ic_school_black_24dp"
        app:fabSize="normal"
        android:visibility="gone"
        android:id="@+id/fab_school"
        app:backgroundTint="@color/fab1"
        app:pressedTranslationZ="12dp"/>
and the last one
<android.support.design.widget.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/fab_margin"
        android:layout_gravity="bottom|end"
        android:elevation="6dp"
        android:src="@drawable/ic_share_black_24dp"
        app:fabSize="normal"
        android:id="@+id/main_fab"
        app:pressedTranslationZ="12dp"/>

Note: if you have any dought you can check full activity.xml code on GitHub.

Now time for java code.
In my case java file is MainActivty.java Add those variables-
FloatingActionButton main,people,school;
Animation fabOpen,fabClose,fabRotate,fabRotateAntiClockWise;

//fab is open or close
boolean isOpen = false;
Now assign all fab button with findViewById()
main = (FloatingActionButton) findViewById(R.id.main_fab);
people = (FloatingActionButton) findViewById(R.id.fab_people);
school = (FloatingActionButton) findViewById(R.id.fab_school);
Now time for load animation-
fabOpen = AnimationUtils.loadAnimation(this,R.anim.fab_open);
fabClose = AnimationUtils.loadAnimation(this,R.anim.fab_close);
fabRotate = AnimationUtils.loadAnimation(this,R.anim.rotate_clockwise);
fabRotateAntiClockWise = AnimationUtils.loadAnimation(this,R.anim.rotate_anit_clockwise);

If the user clicks the main fab button then we will show others button. That's is the logic. ok add main fab clickListener and use below code to show others button. After the code, I discuss code logic again Ok enough talking. Let's start-

main.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Log.e("Click", "click");

                if (isOpen){
                    people.setAnimation(fabClose);
                    school.setAnimation(fabClose);
                    main.setAnimation(fabRotateAntiClockWise);
                    people.setClickable(false);
                    school.setClickable(false);
                    people.setVisibility(View.GONE);
                    school.setVisibility(View.GONE);
                    isOpen = false;

                } else {
                    people.setVisibility(View.VISIBLE);
                    school.setVisibility(View.VISIBLE);
                    people.setAnimation(fabOpen);
                    school.setAnimation(fabOpen);
                    main.setAnimation(fabRotate);
                    people.setClickable(true);
                    school.setClickable(true);
                    people.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Toast.makeText(MainActivity.this, "Welcome to people", 
                                      Toast.LENGTH_SHORT).show();
                        }
                    });

                    school.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Toast.makeText(MainActivity.this, "Welcome to school", 
                                                      Toast.LENGTH_SHORT).show();
                        }
                    });

                    isOpen = true;
                }
            }
        });

Note: youcan recheck MainActivity.java on GitHub 

Code analysis-
1.In layout file when we created out floating action button we set those button's visibility gone excepts main fab button. we check boolean state first, isopen is true or false

2. If the answer is true that means fab is open now. So we set here close fab functionality.
2.1. set close animation on two fabs that are you want's to close.
2.2. set those fab clickable false.
2.3 set anti clock rotate animation on mainFab.
2.4 now time to invisible that's fab.
2.5 at last assign isopen to false.

3.If the answer is false that means fab is close. So we set here close fab functionality.
3.1. now time to invisible others fab.
3.1. set open animation on two fabs that are not shown.
3.2. set those fab clickable true.
3.3 set clock rotate animation on mainFab.
3.4 set click listener on those fab
3.5 at last assign isopen to true.

Wow. now we fab three fabs in our layout but only one is showing at first. After clicking main fab other's button is open with animation. And those button is now working. And again click the main fab button, others two buttons is gone. So welcome to you all. you successfully created this project.

you can find the full project on Github. Fab

Thanks for reading this post and hope this code is working and now you can use fab with animation on your own project.

Happy coding.

Read More