Tuesday, 10 January 2017

Recycler View in Android


STEP 1 :

compile 'com.android.support:cardview-v7:25.0.1'
compile 'com.android.support:recyclerview-v7:25.0.1'
compile 'com.android.support:design:25.0.1'

STEP 2 :
Create custom_layout.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="wrap_content"

    xmlns:app="http://schemas.android.com/apk/res-auto"

    android:orientation="vertical">



    <android.support.v7.widget.CardView

        android:id="@+id/card"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        app:cardBackgroundColor="@color/colorPrimary"

        app:cardUseCompatPadding="true"

        >



        <LinearLayout

            android:layout_width="match_parent"

            android:layout_height="match_parent"

            android:orientation="vertical">



            <TextView

                android:id="@+id/tname"

                android:layout_width="match_parent"

                android:layout_height="wrap_content"

                android:textSize="20sp"

                android:text="Name"/>



            <Button

                android:text="Button"

                android:layout_width="match_parent"

                android:layout_height="wrap_content"

                android:id="@+id/btn1" />



            <Button

                android:text="Button"

                android:layout_width="match_parent"

                android:layout_height="wrap_content"

                android:id="@+id/btn2" />



            <TextView

                android:id="@+id/taddress"

                android:layout_width="match_parent"

                android:layout_height="wrap_content"

                android:textSize="20sp"

                android:text="address"/>



        </LinearLayout>

    </android.support.v7.widget.CardView>



</LinearLayout>
STEP 3 : Create activity_main.xml
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:id="@+id/activity_main"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    tools:context=".MainActivity">



  <android.support.v7.widget.RecyclerView

      android:id="@+id/recycler"

      android:layout_width="match_parent"

      android:layout_height="match_parent"

      android:scrollbars="vertical"/>

</RelativeLayout>


STEP 4 : create package GetSet and adapter

STEP 5 : Create User.java in GetSet
package com.app.ydoodle.customadapter.getset;



public class user {

    String name;

    String address;



    public String getId() {

        return id;

    }



    public void setId(String id) {

        this.id = id;

    }



    String id;



    public String getAddress() {

        return address;

    }



    public void setAddress(String address) {

        this.address = address;

    }



    public String getName() {

        return name;

    }



    public void setName(String name) {

        this.name = name;

    }

}


Step 6 : Create CustomViewHolder.java inside adapter folder
package com.app.ydoodle.customadapter.adapter;



import android.support.v7.widget.CardView;

import android.support.v7.widget.RecyclerView;

import android.view.View;

import android.widget.Button;

import android.widget.TextView;



import com.app.ydoodle.customadapter.R;



public class CustomViewHolder extends RecyclerView.ViewHolder {

    CardView card;

    TextView name,address;

    Button b1,b2;



    public CustomViewHolder(View itemView) {

        super(itemView);

        name = (TextView) itemView.findViewById(R.id.tname);

        address = (TextView) itemView.findViewById(R.id.taddress);

        card = (CardView) itemView.findViewById(R.id.card);

        b1= (Button) itemView.findViewById(R.id.btn1);

        b2= (Button) itemView.findViewById(R.id.btn2);







    }

}

Step 7 : create RecyclerAdapter.java
package com.app.ydoodle.customadapter.adapter;



import android.content.Context;

import android.support.v7.widget.RecyclerView;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import android.widget.Toast;



import com.app.ydoodle.customadapter.R;

import com.app.ydoodle.customadapter.getset.user;



import java.util.List;



public class RecyclerAdapter extends RecyclerView.Adapter<CustomViewHolder> {



    Context mContext;

    List<user> feedItem;



    public RecyclerAdapter(Context mContext, List<user> feedItem) {

        this.mContext = mContext;

        this.feedItem = feedItem;

    }



    @Override

    public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_layout, parent, false);

        CustomViewHolder holder = new CustomViewHolder(view);

        return holder;

    }



    @Override

    public void onBindViewHolder(CustomViewHolder holder, int position) {

        final user u = feedItem.get(position);

        holder.name.setText(u.getName());

        holder.address.setText(u.getAddress());



        holder.card.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View view) {

                Toast.makeText(mContext, "Clicked : " + u.getId(), Toast.LENGTH_SHORT).show();

            }

        });



        holder.b1.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                Toast.makeText(mContext, "b1 :" + u.getId(), Toast.LENGTH_SHORT).show();

            }

        });





    }



    @Override

    public int getItemCount() {

        return feedItem.size();

    }

}


Step 8 : MainActivity.java
package com.app.ydoodle.customadapter;



import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

import android.support.v7.widget.LinearLayoutManager;

import android.support.v7.widget.RecyclerView;

import android.util.Log;



import com.app.ydoodle.customadapter.adapter.RecyclerAdapter;

import com.app.ydoodle.customadapter.getset.user;



import java.util.ArrayList;

import java.util.List;



public class MainActivity extends AppCompatActivity {



    RecyclerView recyclerView;



    List<user> detail;



    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

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

        recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));



        detail = new ArrayList<>();





        for (int i = 0; i < 20; i++) {

            user u = new user();

            u.setName("Miraj");

            u.setAddress("Jungi");

            u.setId(String.valueOf(i));

            detail.add(u);

            Log.i("testing :" , String.valueOf(i));

        }



        RecyclerAdapter adapter = new RecyclerAdapter(MainActivity.this, detail);

        recyclerView.setAdapter(adapter);



    }

}


Monday, 9 January 2017

Change Toolbar Title in Android


Write this in onCrete() :-

getSupportActionBar().setTitle("Your Title");

Sunday, 8 January 2017

Navigation Drawer in Andorid



STEP 1 :

  compile 'com.android.support:design:25.1.0'

STEP 2 :
Right click on res folder ->New -> Android resource directory ->Select Resource type to menu and click enter to create menu directory under res folder

STEP 3 :
Create a  menu/drawer_view.xml file: 

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_first_fragment"
            android:icon="@mipmap/ic_launcher"
            android:title="First" />
        <item
            android:id="@+id/nav_second_fragment"
            android:icon="@mipmap/ic_launcher"
            android:title="Second" />
        <item
            android:id="@+id/nav_third_fragment"
            android:icon="@mipmap/ic_launcher"
            android:title="Third" />
    </group>
</menu>
 
STEP 4 :
Create a new layout file res/layout/toolbar.xml with the following code:

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:fitsSystemWindows="true"
    android:minHeight="?attr/actionBarSize"
    app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    android:background="?attr/colorPrimaryDark">
</android.support.v7.widget.Toolbar>

STEP 5 :
Create nav_header.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="192dp"
    android:background="@drawable/back"
    android:padding="16dp"
    android:theme="@style/ThemeOverlay.AppCompat.Dark">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="MiHome"
        android:textColor="@android:color/white"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1"
        android:textSize="30dp"
        android:id="@+id/textView2"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

STEP 6 :

Setup Drawer in Activity
Next, let's setup a basic navigation drawer based on the following layout file which has the entire drawer setup in res/layout/activity_main.xml. Note that the Toolbar is added as the first child of the main content view by adding the include tag.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- This LinearLayout represents the contents of the screen  -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <!-- The ActionBar displayed at the top -->
        <include
            layout="@layout/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <!-- The main content view where fragments are loaded -->
        <FrameLayout
            android:id="@+id/flContent"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </LinearLayout>

    <!-- The navigation drawer that comes from the left -->
    <!-- Note that `android:layout_gravity` needs to be set to 'start' -->
    <android.support.design.widget.NavigationView
        android:id="@+id/nvView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="@android:color/white"
        app:menu="@menu/drawer_view"
        app:headerLayout="@layout/nav_header"/>

</android.support.v4.widget.DrawerLayout>
 
STEP 7 :

In your res/values/strings.xml add the following:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="drawer_open">Open navigation drawer</string>
    <string name="drawer_close">Close navigation drawer</string>
</resources>

STEP 8 :
create OneFragment.java TwoFragment.java and ThreeFragment.java

fragment_one.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".OneFragment">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/one"
        android:textSize="40dp"
        android:textStyle="bold"
        android:layout_centerInParent="true"/>
</RelativeLayout>

OneFragment.java

import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class OneFragment extends Fragment{
    public OneFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_one, container, false);
    }
}

STEP 9 :
Now, let's setup the drawer in our activity. We can also setup the menu icon too.

package com.example.admin.navigationdrawer;
import android.content.res.Configuration;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.Fragmentanager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {
    private DrawerLayout mDrawer;
    private Toolbar toolbar;
    private NavigationView nvDrawer;

    // Make sure to be using android.support.v7.app.ActionBarDrawerToggle version.
    // The android.support.v4.app.ActionBarDrawerToggle has been deprecated.
    private ActionBarDrawerToggle drawerToggle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Set a Toolbar to replace the ActionBar.
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Find our drawer view
        mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        nvDrawer = (NavigationView) findViewById(R.id.nvView);
        // Setup drawer view
        setupDrawerContent(nvDrawer);
        drawerToggle = setupDrawerToggle();
        // Tie DrawerLayout events to the ActionBarToggle
        mDrawer.addDrawerListener(drawerToggle);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        drawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggles
        drawerToggle.onConfigurationChanged(newConfig);
    }

    private ActionBarDrawerToggle setupDrawerToggle() {
        // NOTE: Make sure you pass in a valid toolbar reference.  ActionBarDrawToggle() does not require it
        // and will not render the hamburger icon without it.
        return new ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.drawer_openR.string.drawer_close);
    }

    private void setupDrawerContent(NavigationView navigationView) {
        navigationView.setNavigationItemSelectedListener(
                new NavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(MenuItem menuItem) {
                        selectDrawerItem(menuItem);
                        return true;
                    }
                });
    }

    public void selectDrawerItem(MenuItem menuItem) {
        // Create a new fragment and specify the fragment to show based on nav item clicked
        Fragment fragment = null;
        Class fragmentClass;
        switch(menuItem.getItemId()) {
            case R.id.nav_first_fragment:
                fragmentClass = OneFragment.class;
                break;
            case R.id.nav_second_fragment:
                fragmentClass = TwoFragment.class;
                break;
            case R.id.nav_third_fragment:
                fragmentClass = ThreeFragment.class;
                break;
            default:
                fragmentClass = OneFragment.class;
        }
        try {
            fragment = (Fragment) fragmentClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Insert the fragment by replacing any existing fragment
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
        // Highlight the selected item has been done by NavigationView
        menuItem.setChecked(true);
        // Set action bar title
        setTitle(menuItem.getTitle());
        // Close the navigation drawer
        mDrawer.closeDrawers();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // The action bar home/up action should open or close the drawer.
        if (drawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        switch (item.getItemId()) {
            case android.R.id.home:
                mDrawer.openDrawer(GravityCompat.START);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}


Add in style.xml 
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>


Saturday, 7 January 2017

Android Material Tab Layout with custom views




STEP 1 :
Open build.gradle and add android design support library com.android.support:design:25.1.0

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:25.1.0'
    compile 'com.android.support:design:25.1.0'
}

STEP 2 :
Open colors.xml located under res values and add the below color values.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color
name="colorPrimary">#125688</color>
    <color
name="colorPrimaryDark">#125688</color>
    <color
name="textColorPrimary">#FFFFFF</color>
    <color
name="windowBackground">#FFFFFF</color>
    <color
name="navigationBarColor">#000000</color>
    <color
name="colorAccent">#c8e8ff</color>
</resources>

STEP 3 :
Add the below dimensions to dimens.xml located under res values.
<resources>
<dimen name="activity_horizontal_margin">16dp</dimen>
<dimen name="activity_vertical_margin">16dp</dimen>
<dimen name="tab_max_width">264dp</dimen>
<dimen name="tab_padding_bottom">16dp</dimen>
<dimen name="tab_label">14sp</dimen>
<dimen name="custom_tab_layout_height">72dp</dimen>
</resources>

STEP 4 :
Open styles.xml located under res values and add below styles. The styles defined in this styles.xml are common to all the android versions.

<resources>
    <style name="MyMaterialTheme" parent="MyMaterialTheme.Base">
    </style>
    <style name="MyMaterialTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="windowNoTitle">true</item>
        <item name="windowActionBar">false</item>
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
</resources>

STEP 5 :
Finally open AndroidManifest.xml and modify the theme to our customized theme by changing the android:theme attribute value.

android:theme="@style/MyMaterialTheme"

STEP 6 :
Under your main package create a fragment named OneFragment.java and add the below code.

public class OneFragment extends Fragment{
    public OneFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_one, container, false);
    }
}

STEP 7 :
Open fragment_one.xml located under res layout and do the below changes.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".OneFragment">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/one"
        android:textSize="40dp"
        android:textStyle="bold"
        android:layout_centerInParent="true"/>
</RelativeLayout>

STEP 8 :
Likewise create few more fragment activities with same code we used for OneFragment.java. I have created TwoFragment.java, ThreeFragment.java

STEP 9 :
Open the layout file of main activity (activity_main.xml) and add below layout code.
app:tabMode – Defines the mode of the tab layout. In our case the value should be “fixed

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" >

            </android.support.v7.widget.Toolbar>

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabMode="fixed"
            app:tabGravity="fill"/>

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

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"  />

    </LinearLayout>
</android.support.design.widget.CoordinatorLayout>

STEP 10 :

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import java.util.ArrayList;
import java.util.List;

public class Home extends AppCompatActivity {

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);
        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new OneFragment(), "ONE");
        adapter.addFragment(new TwoFragment(), "TWO");
        adapter.addFragment(new ThreeFragment(), "THREE");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }
}

Note :
Import this :- import android.support.v4.app.Fragment; in Home.java