Wednesday, 5 December 2018

Kotlin-Create TextView Programatically

Hello Friends,
      In this tutorial I am going create a textview dynamically in kotlin and add it to Linearlayout layout.

1. activity_main.xml: Following is the activity_main.xml containing the TextView with the text .

<?xml version="1.0" encoding="utf-8"?>  
 <android.support.constraint.ConstraintLayout xmlns:android="https://schemas.android.com/apk/res/android"  
  xmlns:app="http://schemas.android.com/apk/res-auto"  
  xmlns:tools="http://schemas.android.com/tools"  
  android:layout_width="match_parent"  
  android:layout_height="match_parent"  
  tools:context=".TextViewSample">  
  <LinearLayout  
   android:id="@+id/ll_main_layout"  
   android:layout_width="match_parent"  
   android:layout_height="wrap_content"  
   android:orientation="vertical">  
   <TextView  
    android:id="@+id/tv_static"  
    android:layout_width="wrap_content"  
    android:layout_height="wrap_content"  
    android:textSize="20sp"  
    android:padding="20sp"  
    android:justificationMode="inter_word"  
    android:text="This textview is created from xml"/>  
  </LinearLayout>  
 </android.support.constraint.ConstraintLayout>

2. Creation of textview dynamically,
val tv_programtically = TextView(this)
tv_programtically.textSize = 20f
tv_programtically.text = "This textview is an dynamic textview in kotlin"

3. Finally the complete code is:

  TextViewSample.kt
package com.android.developer.kotlinsample

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.LinearLayout
import android.widget.TextView
class TextViewSample : AppCompatActivity() {

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_text_view_sample)

    /** Dynamic creation of text view */
    val tv_programtically = TextView(this)
    tv_programtically.textSize = 20f
    tv_programtically.text = "This textview is an dynamic textview in kotlin"
    /**------end--------**/

    // add TextView to LinearLayout
    val ll_main_layout = findViewById(R.id.ll_main_layout) as LinearLayout
    ll_main_layout.addView(tv_programtically)
  }
}
Hope this will help some one. Enjoy Coding.... :)

Kotlin-bind OnClickListener on view

Hello Friends,
 In this tutorial I am showing you how to bind the click listener on View in Kotlin.

1. Code snippet to set OnClickListener on Textview in Kotlin Android
val tvStatic = findViewById(R.id.tv_static) as TextView
tvStatic.setOnClickListener {
 // your code to perform when the user clicks on the TextView
 Toast.makeText(this, "You clicked on TextView 'Click Me'.", Toast.LENGTH_SHORT).show()
}

2. Code snippet to set OnClickListener on Button in Kotlin Android
// get reference to button
val btn_click = findViewById(R.id.btn_click_me) as Button
// set on-click listener
btn_click.setOnClickListener {
    Toast.makeText(this@MainActivity, "You clicked on Button.", Toast.LENGTH_SHORT).show()
}

3. Code snippet to set OnClickListener on ImageView in Kotlin Android
// get reference to ImageView
val iv_profile = findViewById(R.id.image_view) as ImageView
// set on-click listener for ImageView
iv_profile.setOnClickListener {
    // your code here
}

Hope this will help someone.
Enjoy Coding..... :)

Saturday, 23 June 2018

Android Live Data Tutorial | Live Data | Data Binding | Architecture Components

Hello Friends,
              Today I am going to share me small tutorial of LiveData with Data Binding.

-What is LiveData?
     LiveData is an observable data holder class that can be observed within
     a given lifecycle. It lets the components in your app, usually the UI,
     observe LiveData objects for changes.

-The advantages of using LiveData

  •      Ensures your UI matches your data state
  •      No memory leaks
  •      No crashes due to stopped activities
  •      No more manual lifecycle handling
  •      Always up to date data
  •      Proper configuration changes
  •      Sharing resources
-How to use it in our app

   a. Add below dependency in app/build.gradle

implementation "android.arch.lifecycle:extensions:1.1.1" 


   
   b. UserViewModel.java : Creating a ViewModel class

package com.android.developer.livedatademo.model;

import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.ViewModel;

/**
 * Created by mukesh on 13/6/18.
 */
public class UserViewModel extends ViewModel {

    // Create a LiveData with a String
    private MutableLiveData mUser;

    public MutableLiveData getUser() {
        if (mUser == null) {
            mUser = new MutableLiveData();
        }
        return mUser;
    }
} 

In Activity class we creates an observer which updates the ui.
final Observer nameObserver = new Observer() {
      @Override
      public void onChanged(@Nullable final User user) {
      // Update the UI, in this case, a TextView.
      binding.tvUserName.setText(user.getName());
    }
};

Next step is observe the livedata, passing in the activity as a LifecycleOwner and the Observer.
userViewModel.getUser().observe(this, nameObserver);
binding.btnClick.setOnClickListener(this); 

The complete code,

package com.android.developer.livedatademo;

import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.databinding.DataBindingUtil;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

import com.android.developer.livedatademo.databinding.ActivityMainBinding;
import com.android.developer.livedatademo.model.User;
import com.android.developer.livedatademo.model.UserViewModel;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    UserViewModel userViewModel;
    ActivityMainBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        // Get the ViewModel.
        userViewModel = ViewModelProviders.of(this).get(UserViewModel.class);
        // Create the observer which updates the UI.
        final Observer nameObserver = new Observer() {
            @Override
            public void onChanged(@Nullable final User user) {
                // Update the UI, in this case, a TextView.
                binding.tvUserName.setText(user.getName());
            }
        };

        // Observe the LiveData, passing in this activity as the LifecycleOwner and the observer.
        userViewModel.getUser().observe(this, nameObserver);
        binding.btnClick.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        User user = new User();
        user.setName("Mukesh Yadav");
        user.setAge("25");
        userViewModel.getUser().setValue(user);
    }
} 

Download the complete code here

Hope this will helps someone.
Enjoy Coding... :)

Sunday, 17 December 2017

Android MVP for Beginners | Android MVP tutorial | Model-View-Presenter: Android | Android Architecture with MVP

Hello Friends,
          Today I am  going to share a very simple example of Android MVP.
In this sample I am using MVP pattern for network call and and user
form(login form) data validation which is mainly used in most of the android
application.

Model View Presenter divides application into three layers i.e: Model, View and Presenter.
  1. Model: This handles the data part of our application
  2. Presenter: It acts as a bridge that connects a Model and a View.
  3. View: This is responsible for laying out views with the relevant data as instructed by the Presenter     

Note: The View never communicates with Model directly

1. LoginActivity.java 
package android.developer.solutions.androidmvp.activity.login.view;

import android.content.Intent;
import android.developer.solutions.androidmvp.R;
import android.developer.solutions.androidmvp.activity.home.view.HomeActivity;
import android.developer.solutions.androidmvp.activity.login.interactor.LoginInteractorImpl;
import android.developer.solutions.androidmvp.activity.login.presenter.ILoginPresenter;
import android.developer.solutions.androidmvp.activity.login.presenter.LoginPresenterImpl;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;

public class LoginActivity extends AppCompatActivity implements ILoginView {
    EditText username;
    EditText password;
    ProgressBar progress;
    Button button;
    private ILoginPresenter presenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        progress = (ProgressBar) findViewById(R.id.progress);
        button = (Button) findViewById(R.id.btnLogin);
        password = (EditText) findViewById(R.id.password);
        username = (EditText) findViewById(R.id.username);
        presenter = new LoginPresenterImpl(this, new LoginInteractorImpl());
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                presenter.validateCredentials(username.getText().toString(), password.getText().toString());
            }
        });
    }

    @Override
    protected void onDestroy() {
        presenter.onDestroy();
        super.onDestroy();
    }

    @Override
    public void showProgress() {
        progress.setVisibility(View.VISIBLE);
    }

    @Override
    public void hideProgress() {
        progress.setVisibility(View.GONE);
    }

    @Override
    public void setUsernameError() {
        username.setError("Invalid user name");
    }

    @Override
    public void setPasswordError() {
        password.setError("Invalid password");
    }

    @Override
    public void navigateToHome() {
        startActivity(new Intent(this, HomeActivity.class));
        finish();
    }
}


2. ILoginView.java

package android.developer.solutions.androidmvp.activity.login.view;

/**
 * Created by Mukesh on 12/16/2017.
 * androiddevelopersolutions.com
 */
public interface ILoginView {
    void showProgress();
    void hideProgress();
    void setUsernameError();
    void setPasswordError();
    void navigateToHome();
}


Download complete code from here

Hope this will helps some one.
Enjoy Coding............ :)

Monday, 27 November 2017

Android O: Fonts – Part 1 | Working with custom font Android O | Custom font | Fonts in XML

Hello Friends,
              Android 8.0 (API level 26) introduces a new feature, Fonts in XML, which lets you use fonts as resources. You can add the font file in the res/font/ folder to bundle fonts as resources. These fonts are compiled in your R file and are automatically available in Android Studio. You can access the font resources with the help of a new resource type, font. For example, to access a font resource, use @font/myfont, or R.font.myfont.

To use the Fonts in XML feature on devices running Android API version 14 and higher, use the Support Library 26. For more information on using the support library, refer to the Using the support library section.

Steps

  • To add fonts as resources, perform the following steps in the Android Studio

    • Right-click the res folder and go to New > Android resource directory       
    • The New Resource Directory window appears.


    • In the Resource type list, select font, and then click OK.






      Note: The name of the resource directory must be font.

  • Using fonts in XML layouts 
    • In the layout XML file, set the font Family attribute to the font file you want to access.






    Download Complete code from here.
    Hope this will help some one.
    Enjoy coding..................  ;)   

Thursday, 23 November 2017

Android Firebase | Android Push Notifications using Firebase Cloud Messaging FCM

Hello Friends,
               Google moved from Google Cloud Messaging (GCM) to Firebase Cloud Messaging (FCM). Just like GCM, FCM is a cross-platform messaging solution that allows you to send messages. FCM is completely free and there are no limitations.

  • Firebase Message types : Using FCM you can send three types of messages i.e:
    • Notification Message
    • Data Message
    • both Notification & Data Payload


  • Integrating Firebase Cloud Messaging 
    • First thing you need to do is go to https://firebase.google.com/ and make an account to gain access to their console. After you gain access to the console you can start by creating your first project.
    • Give the package name of your project in which you are going to integrate the Firebase. Here the google-services.json file will be downloaded when you press add app button.


     



1. MainActivity.java
package android.developer.solutions.firebasenotification.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.developer.solutions.firebasenotification.R;
import android.developer.solutions.firebasenotification.app.Config;
import android.developer.solutions.firebasenotification.util.NotificationUtils;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.google.firebase.messaging.FirebaseMessaging;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();
    private BroadcastReceiver mRegistrationBroadcastReceiver;
    private TextView txtRegId, txtMessage;

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

        txtRegId = (TextView) findViewById(R.id.txt_reg_id);
        txtMessage = (TextView) findViewById(R.id.txt_push_message);

        mRegistrationBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                // checking for type intent filter
                if (intent.getAction().equals(Config.REGISTRATION_COMPLETE)) {
                    // gcm successfully registered
                    // now subscribe to global` topic to receive app wide notifications
                    FirebaseMessaging.getInstance().subscribeToTopic(Config.TOPIC_GLOBAL);

                    displayFirebaseRegId();

                } else if (intent.getAction().equals(Config.PUSH_NOTIFICATION)) {
                    // new push notification is received

                    String message = intent.getStringExtra("message");
                    Toast.makeText(getApplicationContext(), "Push notification: " + message, Toast.LENGTH_LONG).show();
                    txtMessage.setText(message);
                }
            }
        };

        displayFirebaseRegId();
    }

    // Fetches reg id from shared preferences
    // and displays on the screen
    private void displayFirebaseRegId() {
        SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0);
        String regId = pref.getString("regId", null);

        Log.e(TAG, "Firebase reg id: " + regId);

        if (!TextUtils.isEmpty(regId))
            txtRegId.setText("Firebase Reg Id: " + regId);
        else
            txtRegId.setText("Firebase Reg Id is not received yet!");
    }

    @Override
    protected void onResume() {
        super.onResume();

        // register GCM registration complete receiver
//        LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
//                new IntentFilter(Config.REGISTRATION_COMPLETE));

        // register new push message receiver
        // by doing this, the activity will be notified each time a new message arrives
        LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
                new IntentFilter(Config.PUSH_NOTIFICATION));

        // clear the notification area when the app is opened
        NotificationUtils.clearNotifications(getApplicationContext());
    }

    @Override
    protected void onPause() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
        super.onPause();
    }
}




2. MyFirebaseInstanceIDService.java

package android.developer.solutions.firebasenotification.service;

import android.content.Intent;
import android.content.SharedPreferences;
import android.developer.solutions.firebasenotification.app.Config;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;


/**
 * Created by Mukesh on 10/02/17.
 * www.androiddevelopersolutions.com/
 */
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
    private static final String TAG = MyFirebaseInstanceIDService.class.getSimpleName();

    @Override
    public void onTokenRefresh() {
        super.onTokenRefresh();
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();

        // Saving reg id to shared preferences
        storeRegIdInPref(refreshedToken);

        // sending reg id to your server
        sendRegistrationToServer(refreshedToken);

        // Notify UI that registration has completed, so the progress indicator can be hidden.
        Intent registrationComplete = new Intent(Config.REGISTRATION_COMPLETE);
        registrationComplete.putExtra("token", refreshedToken);
        LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
    }

    private void sendRegistrationToServer(final String token) {
        // sending gcm token to server
        Log.e(TAG, "sendRegistrationToServer: " + token);
    }

    private void storeRegIdInPref(String token) {
        SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0);
        SharedPreferences.Editor editor = pref.edit();
        editor.putString("regId", token);
        editor.commit();
    }
}


3. MyFirebaseMessagingService.java
package android.developer.solutions.firebasenotification.service;

import android.content.Context;
import android.content.Intent;
import android.developer.solutions.firebasenotification.activity.MainActivity;
import android.developer.solutions.firebasenotification.app.Config;
import android.developer.solutions.firebasenotification.util.NotificationUtils;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

import org.json.JSONException;
import org.json.JSONObject;


/**
 * Created by Mukesh on 10/02/17.
 * www.androiddevelopersolutions.com/
 */
public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = MyFirebaseMessagingService.class.getSimpleName();

    private NotificationUtils notificationUtils;

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.e(TAG, "From: " + remoteMessage.getFrom());

        if (remoteMessage == null)
            return;

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody());
            handleNotification(remoteMessage.getNotification().getBody());
        }

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());

            try {
                JSONObject json = new JSONObject(remoteMessage.getData().toString());
                handleDataMessage(json);
            } catch (Exception e) {
                Log.e(TAG, "Exception: " + e.getMessage());
            }
        }
    }

    private void handleNotification(String message) {
        if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
            // app is in foreground, broadcast the push message
            Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
            pushNotification.putExtra("message", message);
            LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

            // play notification sound
            NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
            notificationUtils.playNotificationSound();
        } else {
            // If the app is in background, firebase itself handles the notification
        }
    }

    private void handleDataMessage(JSONObject json) {
        Log.e(TAG, "push json: " + json.toString());

        try {
            JSONObject data = json.getJSONObject("data");

            String title = data.getString("title");
            String message = data.getString("message");
            boolean isBackground = data.getBoolean("is_background");
            String imageUrl = data.getString("image");
            String timestamp = data.getString("timestamp");
            JSONObject payload = data.getJSONObject("payload");

            Log.e(TAG, "title: " + title);
            Log.e(TAG, "message: " + message);
            Log.e(TAG, "isBackground: " + isBackground);
            Log.e(TAG, "payload: " + payload.toString());
            Log.e(TAG, "imageUrl: " + imageUrl);
            Log.e(TAG, "timestamp: " + timestamp);


            if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
                // app is in foreground, broadcast the push message
                Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
                pushNotification.putExtra("message", message);
                LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

                // play notification sound
                NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
                notificationUtils.playNotificationSound();
            } else {
                // app is in background, show the notification in notification tray
                Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);
                resultIntent.putExtra("message", message);

                // check for image attachment
                if (TextUtils.isEmpty(imageUrl)) {
                    showNotificationMessage(getApplicationContext(), title, message, timestamp, resultIntent);
                } else {
                    // image is present, show notification with image
                    showNotificationMessageWithBigImage(getApplicationContext(), title, message, timestamp, resultIntent, imageUrl);
                }
            }
        } catch (JSONException e) {
            Log.e(TAG, "Json Exception: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
    }

    /**
     * Showing notification with text only
     */
    private void showNotificationMessage(Context context, String title, String message, String timeStamp, Intent intent) {
        notificationUtils = new NotificationUtils(context);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        notificationUtils.showNotificationMessage(title, message, timeStamp, intent);
    }

    /**
     * Showing notification with text and image
     */
    private void showNotificationMessageWithBigImage(Context context, String title, String message, String timeStamp, Intent intent, String imageUrl) {
        notificationUtils = new NotificationUtils(context);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        notificationUtils.showNotificationMessage(title, message, timeStamp, intent, imageUrl);
    }
}



4. AndroidManifest.xml



    
        
            
                

                
            
        

        
        
            
                
            
        

        
            
                
            
        
        
    




Download code from here

Hope you like this...
Enjoy Coding..... :)

Tuesday, 19 September 2017

RecyclerView with multiple View Type | RecyclerView with different view types | View Pager inside RecyclerView

Hello Friends,
              Today I am going to share my another android tutorial, with the help
of this we can easily create a Recyclerview with multiple different types
of view .
Also this tutorial helps you to create a View pager inside RecyclerView,


























1. MainActivity.java :

package com.developer.solutions.recyclerviewwithmultipleviewtype.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.widget.TextView;

import com.developer.solutions.recyclerviewwithmultipleviewtype.R;
import com.developer.solutions.recyclerviewwithmultipleviewtype.adapter.MultiViewTypeAdapter;
import com.developer.solutions.recyclerviewwithmultipleviewtype.model.Data;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by Mukesh on 3/8/17.
 * himky02@gmail.com
 */
public class MainActivity extends AppCompatActivity {

    Activity mActivity;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.rv)
    RecyclerView mRecyclerView;
    Unbinder mUnbinder;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //((TextView) findViewById(R.id.tv)).setText("Welcome user");
        mUnbinder = ButterKnife.bind(this);

        ArrayList list = new ArrayList<>();
        list.add(new Data(Data.VIEW_PAGER, "Hello. This is the View Pager view type with images", 0));
        list.add(new Data(Data.IMAGE_TYPE, "A view type with Image and Textview", R.drawable.disneys_cinderella));
        list.add(new Data(Data.AUDIO_TYPE, "Hey, A view type with Button and Textview", 0));
        list.add(new Data(Data.IMAGE_TYPE, "Hi again. A view with Image and Textview", R.drawable.snow));

        MultiViewTypeAdapter adapter = new MultiViewTypeAdapter(list, this);
        final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setAdapter(adapter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
         if (mUnbinder != null) mUnbinder.unbind();
    }
}


2.MultiViewTypeAdapter.java
package com.developer.solutions.recyclerviewwithmultipleviewtype.adapter;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.developer.solutions.recyclerviewwithmultipleviewtype.R;
import com.developer.solutions.recyclerviewwithmultipleviewtype.model.Data;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Mukesh on 3/8/17.
 * himky02@gmail.com
 */
public class MultiViewTypeAdapter extends RecyclerView.Adapter {
    private ArrayList dataSet;
    Context mContext;
    int total_types;
    ArrayList slider_image_list;
    int page = 0;

    public static class TextTypeViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.ll_dots)
        LinearLayout ll_dots;
        @BindView(R.id.vp_slider)
        ViewPager mvViewPager;

        public TextTypeViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    public static class ImageTypeViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.type)
        TextView tvtype;
        @BindView(R.id.img)
        ImageView iv;

        public ImageTypeViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    public static class ButtonTypeViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.type)
        TextView type;
        @BindView(R.id.btn)
        Button btn;

        public ButtonTypeViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    public MultiViewTypeAdapter(ArrayList data, Context context) {
        this.dataSet = data;
        this.mContext = context;
        total_types = dataSet.size();
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view;
        switch (viewType) {
            case Data.VIEW_PAGER:
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.viewpager, parent, false);
                return new TextTypeViewHolder(view);
            case Data.IMAGE_TYPE:
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_image_type, parent, false);
                return new ImageTypeViewHolder(view);
            case Data.AUDIO_TYPE:
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_button_type, parent, false);
                return new ButtonTypeViewHolder(view);
        }
        return null;


    }


    @Override
    public int getItemViewType(int position) {

        switch (dataSet.get(position).type) {
            case 0:
                return Data.VIEW_PAGER;
            case 1:
                return Data.IMAGE_TYPE;
            case 2:
                return Data.AUDIO_TYPE;
            default:
                return -1;
        }
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int listPosition) {

        Data object = dataSet.get(listPosition);
        if (object != null) {
            switch (object.type) {
                case Data.VIEW_PAGER:
                    //((TextTypeViewHolder) holder).type.setText(object.text);
                    slider_image_list = new ArrayList<>();

                    //Add few items to slider_image_list ,this should contain url of images which should be displayed in slider
                    // here i am adding few sample image links, you can add your own

                    slider_image_list.add("http://cdn.collider.com/wp-content/uploads/avengers-movie-banner-scarlett-johansson-jeremy-renner.jpg");
                    slider_image_list.add("http://www.officialterridwyer.com/wp-content/uploads/2015/04/Disneys-Cinderella-2015-Movie-Banner.jpg");
                    slider_image_list.add("http://igmedia.blob.core.windows.net/igmedia/hindi/gallery/movies/raabta/main1.jpg");
                    slider_image_list.add("http://fantoosy.com/wp-content/uploads/2015/11/tamasha.jpg");
                    final SliderPagerAdapter sliderPagerAdapter = new SliderPagerAdapter((Activity) mContext, slider_image_list);
                    ((TextTypeViewHolder) holder).mvViewPager.setAdapter(sliderPagerAdapter);

                    ((TextTypeViewHolder) holder).mvViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                        @Override
                        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                        }

                        @Override
                        public void onPageSelected(int position) {
                            addBottomDots(position, ((TextTypeViewHolder) holder).ll_dots);
                            page = position;
                        }

                        @Override
                        public void onPageScrollStateChanged(int state) {

                        }
                    });
                    addBottomDots(0, ((TextTypeViewHolder) holder).ll_dots);
                    final Handler h = new Handler();
                    h.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (sliderPagerAdapter.getCount() == page) {
                                page = 0;
                            } else {
                                page++;
                            }
                            ((TextTypeViewHolder) holder).mvViewPager.setCurrentItem(page);
                            h.postDelayed(this, 2000);
                        }
                    }, 1000);

                    break;
                case Data.IMAGE_TYPE:
                    ((ImageTypeViewHolder) holder).tvtype.setText(object.text);
                    ((ImageTypeViewHolder) holder).iv.setImageResource(object.data);
                    break;
                case Data.AUDIO_TYPE:
                    ((ButtonTypeViewHolder) holder).type.setText(object.text);
                    ((ButtonTypeViewHolder) holder).btn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Toast.makeText(mContext, "You clicked!!!", Toast.LENGTH_SHORT).show();
                        }
                    });
                    break;
            }
        }

    }

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

    //showing dots on screen
    private void addBottomDots(int currentPage, LinearLayout ll_dots) {
        TextView[] dots = new TextView[slider_image_list.size()];
        ll_dots.removeAllViews();
        for (int i = 0; i < dots.length; i++) {
            dots[i] = new TextView(mContext);
            dots[i].setText(Html.fromHtml("•"));
            dots[i].setTextSize(35);
            dots[i].setTextColor(Color.parseColor("#343434"));
            ll_dots.addView(dots[i]);
        }

        if (dots.length > 0)
            dots[currentPage].setTextColor(Color.parseColor("#A2A2A2"));
    }

}
Download the code from here

Hope this will helps some one.
Enjoy Coding....

 

Copyright @ 2013 Android Developer Blog.