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

Friday, May 19, 2017

Bookstore a java example code

May 19, 2017

Bookstore a java example code
LEVEL: BEGINNER

java


This example is good for understanding
  1. Array
  2. methods
  3. conditions(if and else)
the process of this bookstore: 1.First, we have a collection of books name:
static String[] book = { "java", "c", "c++", "php", "javascript", "html" };
2.we ask the user to which book is he want? 3. we search that book name in our list of books 4. if we find that book we ask again to our user about his occupation 5. because we want to give a discount to our user. here all source code
package com.blogspot.shudiptotrafder;

import java.util.Scanner;

public class BookStore {

    static String[] book = { "java", "c", "c++", "php", "javascript", "html" };
    static Scanner scanner = new Scanner(System.in);

    final static float studentdiscount = .3f;
    final static float teacherdiscount = .2f;
    static boolean flag = true;

    public static void main(String[] args) {
        if (flag) {
            pl("*************WELCOME TO OUR BOOK STORE**********");
        }
        pl("Which book do you want?");
        p("Answer: ");
        String bookname = scanner.nextLine();

        if (bookname.toLowerCase().equals(book[0])) {
            wantedbook(bookname);
            discount();

        } else if (bookname.toLowerCase().equals(book[1])) {
            wantedbook(bookname);
            discount();

        } else if (bookname.toLowerCase().equals(book[2])) {
            wantedbook(bookname);
            discount();

        } else if (bookname.toLowerCase().equals(book[3])) {
            wantedbook(bookname);
            discount();

        } else if (bookname.toLowerCase().equals(book[4])) {
            wantedbook(bookname);
            discount();

        } else if (bookname.toLowerCase().equals(book[5])) {
            wantedbook(bookname);
            discount();

        } else {
            pl("Sorry we don't have " + bookname + " book.");
        }

        pl("\nDo you Want more book?");
        p("Answer: ");
        String ans = scanner.nextLine();
        flag = false;

        if (ans.toLowerCase().equals("yes")) {
            pl("\n");
            String[] ret = null;
            main(ret);
        } else {
            pl("\n");
            pl("********Thank YOU FOR SHOPPING********");
        }

    }

    // methods

    public static void discount() {
        pl("\nAre you Student or Teacher or General Customar?");
        p("Answer: ");
        String userinput = scanner.nextLine();

        if (userinput.toLowerCase().equals("student")) {
            calculateprice(studentdiscount);
        } else if (userinput.toLowerCase().equals("teacher")) {
            calculateprice(teacherdiscount);
        } else {
            pl("You Can not get Discount.");
            pl("your Total Payable Price is 200 TK.");

        }

    }

    public static void calculateprice(float discount) {
        double price = 200;
        price -= price * discount;
        showprice(price);
    }

    public static void showprice(double price) {
        String prices = String.format("%.2f", price);
        pl("your Total Payable Price is : " +prices+ " TK.");

    }

    public static void wantedbook(Object object) {
        pl("You Want " + object + " book. price 200 Tk.");
    }

    public static void p(Object object) {
        System.out.print(object);
    }

    public static void pl(Object object) {
        System.out.println(object);
    }

}

Read More

Java String Example

May 19, 2017

String in Java
java string

Strings Example

Example 1:

Get first two characters of any String
public String firstTwo(String str) {
  if (str.length() >= 2) {
    return str.substring(0, 2);
  } else {
    return str;
  }
  // Solution notes: need an if/else structure to call substring if the length
  // is 2 or more, and otherwise return the string itself
} 

Alternative example of getting first two characters of any strings

public String firstTwo(String str) {

    if (str.length() >= 2) {

        char s = str.charAt(0);
        char s1 = str.charAt(1);

    String string = String.valueOf(s) + s1;
 
 return string;
  }
  return str;
}

Example 2:

get last two characters of any string
public static void main(String[] args) {

    String str = "hello";

    System.out.println(str.substring(str.length()-2));
}

Example 3:

Given a string of even length, return the first half. So the string "WooHoo" yields "Woo".
public String firstHalf(String str) {
  return str.substring(0,(str.length())/2); 
}

Example 4:

Given a string, return a new version without the first and last character
public String withoutEnd(String str) {
    return str.substring(1,str.length()-1);
  }

Example 5:

Given 2 strings, a and b, return a string of the form short+long+short, with the shorter string on the outside and the longer string on the inside
public String comboString(String a, String b) {
  
  int a1 = a.length();
  
  int b1 = b.length();
  
  if(a1 > b1){
     return b+a+b;
  }
  
  return a+b+a;
}

Example 6:

Given 2 strings, return their concatenation, except omit the first char of each.
public String nonStart(String a, String b) {
  
    String s = a.substring(1,a.length());
  
 String s1 = b.substring(1,b.length());
 
 return s+s1;
}

Example 7:

Given a string, return a "rotated left 2" version where the first 2 chars are moved to the end
public String left2(String str) {
  
  if (str.length() >= 2) {
   String s = str.substring(0, 2);
   String s1 = str.substring(2, str.length());
   
   return s1+s;
  }
  return str;
}

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