Tuesday, December 31, 2019

View Pager2 - Kotlin

View Pager2 in Kotlin


ViewPager is an android widget that allows or helps you to change the screen without changing the activity. 
In simpler words, if you want to change the app screen without making an Activity then you can use ViewPager.

So lets start to create sample app by just follow few steps. 


To use View Pager2 in project, follow below mentioned steps
  • Step 1:  Add this dependency in app gradle.
implementation "androidx.viewpager2:viewpager2:1.0.0"

  • Step 2:  Add below code into activity_main.xml

<androidx.viewpager2.widget.ViewPager2
        android:id="@+id/viewPager2"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

  • Step3:  Create Three Fragment (FragmentOne, FragmentTwo, FragmentThree) like below.
class FragmentOne : Fragment(){
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_two, container, false)
    }

    companion object{
        fun newInstance() = FragmentOne()
    }
}
  • Step 4:  And finally add code into our Activity.
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN)
        setContentView(R.layout.activity_main)

        val fragmentList : ArrayList<Fragment> =
            arrayListOf(FragmentOne.newInstance(), FragmentTwo.newInstance(),
                FragmentThree.newInstance())

        val pagerAdapter = ScreenSlidePagerAdapter(this,fragmentList)
        viewPager2.adapter = pagerAdapter


        viewPager2.registerOnPageChangeCallback(
            object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                Log.e("=> ","View pager selected position")
            }
        })
    }

    override fun onBackPressed() {
        if (viewPager2.currentItem == 0) {
            super.onBackPressed()
        } else {
            viewPager2.currentItem = viewPager2.currentItem - 1
        }
    }

    private inner class ScreenSlidePagerAdapter(
        fa : FragmentActivity,
        private val fragments:ArrayList<Fragment>)
        : FragmentStateAdapter(fa) {
        override fun getItemCount(): Int = fragments.size
        override fun createFragment(position: Int): Fragment = fragments[position]
    }
}
You can also download my full source code
https://github.com/sakib143/ViewPager2-Kotlin.git


Friday, December 16, 2016

Firebase Cloud Messaging in Android

Firebase Cloud Messeging.


Firebase Cloud Messaging is a powerful API that lets you deliver messages reliably and independent of the platform you are developing on. Using FCM, developers can notify the users that new data is available for sync and send notification messages. These are very useful for testing, sending marketing and engagement messages. It comes in with built-in targeting and analytics.

Below are step which you need to follow in the implementation.



1>First of all we have to open https://console.firebase.google.com/ and create project
2>then goto the setting and project setting option in ://console.firebase.google.com. and at bottom select android option
  (Add firebase to your android app)
3> Then add package name and SHA1 key then one "google-services.json" file will be automatically download.
4> We should to copy "google-services.json" file into our project like "typically app/" and project should be opne in
   "Project" in android studio.
5>Then we have to add google play services into our project.
6> Select project in android studio in "Project" and add below code in projects's build.gradle (not app's build.gradle).


buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.2'

        classpath 'com.google.gms:google-services:3.0.0'
        // NOTE: Do not place your application dependencies here; they belong

        // in the individual module build.gradle files

    }
}

7> After that we have to add below code into our dependency in build.gradle (app's build.gradle)

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'    })
    compile 'com.android.support:appcompat-v7:25.0.1'

    testCompile 'junit:junit:4.12'

    compile 'com.google.android.gms:play-services:10.0.1'
    compile 'com.google.firebase:firebase-core:10.0.1'
}

apply plugin: 'com.google.gms.google-services'

8> There after we have to add some internet permission and manifest and below is my Manifest.xml

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"    
package="example.com.firebasedemo">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application

        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"

        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>


        <service android:name=".MyFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        <service android:name=".MyFirebaseInstanceIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>


        <meta-data
            android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@drawable/myicon" 
         />
        <!-- Set color used with incoming notification messages. This is used when no color is set for the incoming             notification message. See README(https://goo.gl/6BKBk7) for more. -->        
           <meta-data
            android:name="com.google.firebase.messaging.default_notification_color"
            android:resource="@color/colorAccent" />


    </application>

</manifest>

Below is my activity_main.xml.

<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <ImageView

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginBottom="16dp"
        android:src="@drawable/firebase_lockup_400" />


    <Button
        android:id="@+id/btnSubcribeTopic"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="20dp"
        android:text="subscribe_to_news" />


    <TextView
        android:id="@+id/tvMessege"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp"
        />
</LinearLayout>

And here is my MainActivity Code.

public class MainActivity extends AppCompatActivity {

    private Button btnSubcribeTopic;
    TextView tvMessege;

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

        getId();
        getNotification();


        // to get token        String token = FirebaseInstanceId.getInstance().getToken();
        Log.e("Token is ","=====>"+ token);
        Toast.makeText(MainActivity.this, token, Toast.LENGTH_SHORT).show();

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

                FirebaseMessaging.getInstance().subscribeToTopic("Alert");
                Log.e("You subsribe Alert topic", " >>>>>>>");
                Toast.makeText(MainActivity.this, "Alert Topic subcribe", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void getNotification() {
        try {
            if (getIntent().getExtras() != null) {
                for (String key : getIntent().getExtras().keySet()) {

                    String value = getIntent().getExtras().getString(key);

                    tvMessege.setText(value);
                    Log.e("MainActivity ", "Key: " + key + " and MainActivity  Value: " + value);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getId() {
        try {
            btnSubcribeTopic = (Button) findViewById(R.id.btnSubcribeTopic);
            tvMessege=(TextView)findViewById(R.id.tvMessege);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


Then we have to initialized two class so first is given below.

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

    @Override    public void onTokenRefresh() {

        String refreshedToken = FirebaseInstanceId.getInstance().getToken();

        // Token for server.        sendRegistrationToServer(refreshedToken);
    }

    private void sendRegistrationToServer(String token) {

        Log.e("Token is ", "====>" + token);

    }
}

and another class is also given below.

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    public static String strNotification;

    @Override    public void onMessageReceived(RemoteMessage remoteMessage) {

        Log.e("Notification messege remoteMessage is ","====>"+remoteMessage);

        if (remoteMessage.getData().size() > 0) {
            Log.e("remoteMessage.getData() is ","====>"+remoteMessage.getData());
        }

        if (remoteMessage.getNotification() != null) {
            Log.e("remoteMessage.getNotification().getBody() is ","====>"+remoteMessage.getNotification().getBody());
            strNotification = remoteMessage.getNotification().getBody();
        }
        sendNotification(strNotification);
    }

    private void sendNotification(String messageBody) {
        Intent intent = new Intent(this, MainActivity.class);

        Log.e("sendNotification  ","messageBody????  "+messageBody);

        intent.putExtra("key", messageBody);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(getNotificationIcon())
                .setContentTitle("FCM Message")
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }

    private int getNotificationIcon() {
        boolean whiteIcon = (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP);
        return whiteIcon ? R.drawable.myicon                : R.drawable.ic_launcher;

    }

    // below method is used to show custom icon when application is in background.

    @Override    public void zzm(Intent intent) {
        Intent launchIntent = new Intent(this, MainActivity.class);
        launchIntent.setAction(Intent.ACTION_MAIN);
        launchIntent.addCategory(intent.CATEGORY_LAUNCHER);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* R    equest code */, launchIntent,
                PendingIntent.FLAG_ONE_SHOT);
//        bitmap rawbitmap = bitmapfactory.decoderesource(getresources(),//                R.mipmap.ic_launcher);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.myicon)
//                .setLargeIcon(rawBitmap)

                .setContentTitle(intent.getStringExtra("gcm.notification.title"))
                .setContentText(intent.getStringExtra("gcm.notification.body"))
                .setAutoCancel(true)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }
}




TabLayout example

TabLayout in Android


First of all we have to add below code in dependencies,

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

Below is the style.xml

<resources>

    <!-- 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>

</resources>



Then we have to add below code in activity_main.xml

<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">

    <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.design.widget.TabLayout            
         android:id="@+id/tabLayout"            
         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"  />
</android.support.design.widget.CoordinatorLayout>

Create layout for Fragment.

1> fragment_first.xml
<?xml version="1.0" 
  encoding="utf-8"?>
  <LinearLayout 
   xmlns:android="http://schemas.android.com/apk/res/android"    
   android:orientation="vertical" 
   android:layout_width="match_parent"    
   android:layout_height="match_parent">
    <TextView        
     android:layout_width="wrap_content"        
     android:layout_height="wrap_content"        
     android:text="This is first fragment"        
     android:textColor="@android:color/holo_blue_bright"        
     android:textSize="20sp"         
     android:gravity="center"        
     android:layout_gravity="center_horizontal"        />


</LinearLayout>

Now create FirstFrament class.

public class FirstFragment extends Fragment {

    private View v;

    @Nullable    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Bundle args = getArguments();
        v = inflater.inflate(R.layout.fragment_first, container, false);
        return v;
    }
}

and create SecondFragment class & ThirdFragment class same as above.

Below code is ActivityMain.java class

public class MainActivity extends AppCompatActivity {

    private TabLayout tabLayout;
    private ViewPager viewPager;
    private ViewPagerAdapter viewPagerAdapter;
    private TextView tvTitle;
    public static int currentTab;


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

        getId();
        setViewPager();
        setTabIcon();


        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override            public void onTabSelected(TabLayout.Tab tab) {

                // On third tab we have pass intent to call SecondActivity.

                Log.e("tab ","onTabSelected ===>"+tab.getPosition());
                currentTab = tab.getPosition();
                if(tab.getPosition()==2) {
                    Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                    startActivity(intent);
                }
            }
            @Override            public void onTabUnselected(TabLayout.Tab tab) {
                Log.e("tab ","onTabUnselected ===>"+tab.getPosition());
            }
            @Override            public void onTabReselected(TabLayout.Tab tab) {
                Log.e("tab ","onTabReselected ===>"+tab.getPosition());
            }
        });
    }

    private void setViewPager() {
        // set Adaapter.

        viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(),MainActivity.this);
        viewPager.setAdapter(viewPagerAdapter);
        tabLayout.setupWithViewPager(viewPager);
    }

    private void getId() {
        try {
            tabLayout = (TabLayout) findViewById(R.id.tabLayout);
            viewPager = (ViewPager) findViewById(R.id.viewPager);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // set custom icon to tab in Tablayout.

    private void setTabIcon() {
//        // First Tab

        View firstTab = (View) LayoutInflater.from(this).inflate(R.layout.tab_one_icon, null);
        tvTitle = (TextView) firstTab.findViewById(R.id.tvOne);
        tvTitle.setText("First Tab");
        tabLayout.getTabAt(0).setCustomView(firstTab);

        // Second Tab

        View secondTab = (View) LayoutInflater.from(this).inflate(R.layout.tab_two_icom, null);
        tvTitle = (TextView) secondTab.findViewById(R.id.tvTwo);
        tvTitle.setText("Second Tab");
        tabLayout.getTabAt(1).setCustomView(secondTab);

        //Third Tab

        View thirdTab = (View) LayoutInflater.from(this).inflate(R.layout.tab_three_icon, null);
        tvTitle = (TextView) thirdTab.findViewById(R.id.tvThree);
        tvTitle.setText("Third Tab");
        tabLayout.getTabAt(2).setCustomView(thirdTab);
    }


    @Override    protected void onResume() {
        super.onResume();
        // here in Tab2 we have pass SecondActivity so if we beck from secondActivity then set it to tab 1.        
         if(currentTab==2){
            viewPager.setCurrentItem(1);
        }
    }



    public class ViewPagerAdapter  extends FragmentStatePagerAdapter {

        private Context context;

        public ViewPagerAdapter(FragmentManager fm, MainActivity mainActivity) {
            super(fm);
            context = mainActivity;
            new FirstFragment();
        }

        @Override        public Fragment getItem(int position) {

            switch (position) {
                case 0:
                    FirstFragment firstFragment = new FirstFragment();
                    return firstFragment;

                case 1:
                SecondFragment secondFragment= new SecondFragment ();
                return secondFragment;

                case 2:
                    FirstFragment firstFragment1 = new FirstFragment();
                    return firstFragment1;
                default:
                    return null;
            }
        }

        @Override        public int getCount() {
            return 3;
        }

        @Override        public CharSequence getPageTitle(int position) {
            return " " + position;
        }
    }
}

and we have csutomized tab icon and name so we need to define custom xml in layout folder like below  tab_three_icon


<?xml version="1.0" encoding="utf-8"?><LinearLayout 
xmlns:android="http://schemas.android.com/apk/res/android"    
android:orientation="vertical" 
android:layout_width="match_parent"    
android:layout_height="match_parent"    
android:gravity="center"    >

    <ImageView        
     android:id="@+id/ivIcon"        
      android:layout_width="30dp"        
      android:layout_height="30dp"        
      android:background="@drawable/start_background"        
      android:layout_gravity="center_horizontal"/>

    <TextView        
     android:id="@+id/tvThree"        
     android:layout_width="wrap_content"        
     android:layout_height="wrap_content"        
     android:text="sakljaskljaskljsaklasjkl"        
     android:layout_gravity="center_vertical"        
     android:layout_marginLeft="10dp"/>


</LinearLayout>



and background of custom image view (ivIcon) of tab is.


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

    <item
        android:state_selected="true"        
        android:drawable="@drawable/start_selected" />

    <item
        android:state_selected="false"        
        android:drawable="@drawable/star_unselect" />

</selector>

and in SecondFragment we have  created nested Fragment which containt two tab so layout of this fragment is

second_fragment.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"    
android:orientation="vertical"    
android:layout_width="match_parent"    
android:layout_height="match_parent"    
android:gravity="center">


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

        <android.support.design.widget.TabLayout            
         android:id="@+id/tabLayout"            
         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>


SecondFragment code id blow.

public class SecondFragment  extends Fragment {

    private View v;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private ViewPagerAdapter viewPagerAdapter;
    private TextView tvTitle;

    @Nullable    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Bundle args = getArguments();

        v = inflater.inflate(R.layout.fragment_second, container, false);

        getIds();
        setViewPager();
        setTabIcon();

        return v;
    }
    private void getIds() {
        try {
            tabLayout = (TabLayout) v.findViewById(R.id.tabLayout);
            viewPager = (ViewPager) v.findViewById(R.id.viewPager);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // set custom icon to tab in Tablayout.

    private void setTabIcon() {
//        // First Tab

        View firstTab = (View) LayoutInflater.from(getActivity()).inflate(R.layout.tab_one_icon, null);
        tvTitle = (TextView) firstTab.findViewById(R.id.tvOne);
        tvTitle.setText("Sub One");
        tabLayout.getTabAt(0).setCustomView(firstTab);

        // Second Tab

        View secondTab = (View) LayoutInflater.from(getActivity()).inflate(R.layout.tab_two_icom, null);
        tvTitle = (TextView) secondTab.findViewById(R.id.tvTwo);
        tvTitle.setText("Sub Two");
        tabLayout.getTabAt(1).setCustomView(secondTab);

    }

    private void setViewPager() {
        // set Adaapter.

        viewPagerAdapter = new ViewPagerAdapter(getFragmentManager(), (MainActivity) getActivity());
        viewPager.setAdapter(viewPagerAdapter);
        tabLayout.setupWithViewPager(viewPager);
    }


    public class ViewPagerAdapter  extends FragmentStatePagerAdapter {

        private Context context;

        public ViewPagerAdapter(FragmentManager fm, MainActivity mainActivity) {
            super(fm);
            context = mainActivity;
        }

        @Override        public Fragment getItem(int position) {

            switch (position) {
                case 0:
                    SubFragOne subFragOne = new SubFragOne();
                    return subFragOne;

                case 1:
                    SubFragTwo subFragTwo= new SubFragTwo();
                    return subFragTwo;
                default:
                    return null;
            }
        }

        @Override        public int getCount() {
            return 2;
        }

        @Override        public CharSequence getPageTitle(int position) {
            return " " + position;
        }
    }

}


For more detail check Tablayout_28_11_2016 demo