@Override
 public void setSettingsOnRecyclerView() {
   viewHolder.rvChat.setHasFixedSize(true);
   viewHolder.rvChat.setItemAnimator(new DefaultItemAnimator());
   LinearLayoutManager mLayoutManager = new LinearLayoutManager(mContext);
   mLayoutManager.setReverseLayout(true);
   mLayoutManager.setStackFromEnd(true);
   viewHolder.rvChat.setLayoutManager(mLayoutManager);
   viewHolder.rvChat.addItemDecoration(
       new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL_LIST));
 }
 private LinearLayoutManager createFromConfig() {
   LinearLayoutManager llm =
       new LinearLayoutManager(getActivity(), mConfig.mOrientation, mConfig.mReverseLayout);
   llm.setStackFromEnd(mConfig.mStackFromEnd);
   return llm;
 }
  @Override
  public View onCreateView(
      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);

    View view = inflater.inflate(R.layout.chat_viewer_fragment, container, false);

    contactTitleView = view.findViewById(R.id.contact_title);

    abstractContact = RosterManager.getInstance().getBestContact(account, user);
    contactTitleView.findViewById(R.id.avatar).setOnClickListener(this);

    toolbar = (Toolbar) view.findViewById(R.id.toolbar_default);
    toolbar.inflateMenu(R.menu.chat);
    toolbar.setOnMenuItemClickListener(this);
    toolbar.setNavigationIcon(R.drawable.ic_arrow_left_white_24dp);
    toolbar.setNavigationOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            NavUtils.navigateUpFromSameTask(getActivity());
          }
        });

    setHasOptionsMenu(true);

    accountPainter = new AccountPainter(getActivity());

    sendButton = (ImageButton) view.findViewById(R.id.button_send_message);
    sendButton.setImageResource(R.drawable.ic_button_send_inactive_24dp);

    AbstractChat abstractChat = MessageManager.getInstance().getChat(account, user);

    securityButton = (ImageButton) view.findViewById(R.id.button_security);

    if (abstractChat instanceof RegularChat) {
      securityButton.setOnClickListener(
          new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              showSecurityMenu();
            }
          });
    } else {
      securityButton.setVisibility(View.GONE);
    }

    chatMessageAdapter = new ChatMessageAdapter(getActivity(), account, user, this, this);

    recyclerView = (RecyclerView) view.findViewById(R.id.chat_messages_recycler_view);
    recyclerView.setAdapter(chatMessageAdapter);

    layoutManager = new LinearLayoutManager(getActivity());
    layoutManager.setStackFromEnd(true);
    recyclerView.setLayoutManager(layoutManager);

    inputView = (EditText) view.findViewById(R.id.chat_input);

    view.findViewById(R.id.button_send_message)
        .setOnClickListener(
            new View.OnClickListener() {

              @Override
              public void onClick(View v) {
                sendMessage();
              }
            });

    inputView.setOnKeyListener(
        new View.OnKeyListener() {
          @Override
          public boolean onKey(View view, int keyCode, KeyEvent event) {
            if (SettingsManager.chatsSendByEnter()
                && event.getAction() == KeyEvent.ACTION_DOWN
                && keyCode == KeyEvent.KEYCODE_ENTER) {
              sendMessage();
              return true;
            }
            return false;
          }
        });

    inputView.addTextChangedListener(
        new TextWatcher() {

          @Override
          public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (!skipOnTextChanges && stopTypingTimer != null) {
              stopTypingTimer.cancel();
            }
          }

          @Override
          public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

          @Override
          public void afterTextChanged(Editable text) {
            setUpInputViewButtons();

            if (skipOnTextChanges) {
              return;
            }

            ChatStateManager.getInstance().onComposing(account, user, text);

            stopTypingTimer = new Timer();
            stopTypingTimer.schedule(
                new TimerTask() {
                  @Override
                  public void run() {
                    Application.getInstance()
                        .runOnUiThread(
                            new Runnable() {
                              @Override
                              public void run() {
                                ChatStateManager.getInstance().onPaused(account, user);
                              }
                            });
                  }
                },
                STOP_TYPING_DELAY);
          }
        });

    final ImageButton emojiButton = (ImageButton) view.findViewById(R.id.button_emoticon);
    final View rootView = view.findViewById(R.id.root_view);

    // Give the topmost view of your activity layout hierarchy. This will be used to measure soft
    // keyboard height
    final EmojiconsPopup popup = new EmojiconsPopup(rootView, getActivity());

    // Will automatically set size according to the soft keyboard size
    popup.setSizeForSoftKeyboard();

    // If the emoji popup is dismissed, change emojiButton to smiley icon
    popup.setOnDismissListener(
        new PopupWindow.OnDismissListener() {

          @Override
          public void onDismiss() {
            changeEmojiKeyboardIcon(emojiButton, R.drawable.ic_emoticon_grey600_24dp);
          }
        });

    // If the text keyboard closes, also dismiss the emoji popup
    popup.setOnSoftKeyboardOpenCloseListener(
        new EmojiconsPopup.OnSoftKeyboardOpenCloseListener() {

          @Override
          public void onKeyboardOpen(int keyBoardHeight) {}

          @Override
          public void onKeyboardClose() {
            if (popup.isShowing()) popup.dismiss();
          }
        });

    // On emoji clicked, add it to edittext
    popup.setOnEmojiconClickedListener(
        new EmojiconGridView.OnEmojiconClickedListener() {

          @Override
          public void onEmojiconClicked(Emojicon emojicon) {
            if (inputView == null || emojicon == null) {
              return;
            }

            int start = inputView.getSelectionStart();
            int end = inputView.getSelectionEnd();
            if (start < 0) {
              inputView.append(emojicon.getEmoji());
            } else {
              inputView
                  .getText()
                  .replace(
                      Math.min(start, end),
                      Math.max(start, end),
                      emojicon.getEmoji(),
                      0,
                      emojicon.getEmoji().length());
            }
          }
        });

    // On backspace clicked, emulate the KEYCODE_DEL key event
    popup.setOnEmojiconBackspaceClickedListener(
        new EmojiconsPopup.OnEmojiconBackspaceClickedListener() {

          @Override
          public void onEmojiconBackspaceClicked(View v) {
            KeyEvent event =
                new KeyEvent(0, 0, 0, KeyEvent.KEYCODE_DEL, 0, 0, 0, 0, KeyEvent.KEYCODE_ENDCALL);
            inputView.dispatchKeyEvent(event);
          }
        });

    // To toggle between text keyboard and emoji keyboard keyboard(Popup)
    emojiButton.setOnClickListener(
        new View.OnClickListener() {

          @Override
          public void onClick(View v) {

            // If popup is not showing => emoji keyboard is not visible, we need to show it
            if (!popup.isShowing()) {

              // If keyboard is visible, simply show the emoji popup
              if (popup.isKeyBoardOpen()) {
                popup.showAtBottom();
                changeEmojiKeyboardIcon(emojiButton, R.drawable.ic_keyboard_variant_grey600_24dp);
              }

              // else, open the text keyboard first and immediately after that show the emoji popup
              else {
                inputView.setFocusableInTouchMode(true);
                inputView.requestFocus();
                popup.showAtBottomPending();
                final InputMethodManager inputMethodManager =
                    (InputMethodManager)
                        getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMethodManager.showSoftInput(inputView, InputMethodManager.SHOW_IMPLICIT);
                changeEmojiKeyboardIcon(emojiButton, R.drawable.ic_keyboard_variant_grey600_24dp);
              }
            }

            // If popup is showing, simply dismiss it to show the undelying text keyboard
            else {
              popup.dismiss();
            }
          }
        });

    attachButton = (ImageButton) view.findViewById(R.id.button_attach);
    attachButton.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            onAttachButtonPressed();
          }
        });

    return view;
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    // Load current user card preferences
    Intent intent = getIntent();
    mIdentity = intent.getStringExtra(ApplicationConstants.Extra.IDENTITY);
    mCardId = intent.getStringExtra(ApplicationConstants.Extra.CARD_ID);

    // Initialize Client Factory
    String accessToken = intent.getStringExtra(ApplicationConstants.Extra.VIRGIL_TOKEN);
    clientFactory = new ClientFactory(accessToken);

    // Configure UI
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // Configure messages view
    PrivateKey privateKey =
        new PrivateKey(intent.getStringExtra(ApplicationConstants.Extra.PRIVATE_KEY));
    mMessagesAdapter = new MessagesAdapter(mMessages, mCardId, privateKey);

    RecyclerView messagesRecyclerView = (RecyclerView) findViewById(R.id.messagesRecyclerView);
    LinearLayoutManager layoutManager = new LinearLayoutManager(this);
    // for a chat app, show latest at the bottom
    layoutManager.setStackFromEnd(true);
    messagesRecyclerView.setLayoutManager(layoutManager);
    messagesRecyclerView.setAdapter(mMessagesAdapter);

    mWriteMessageEditText = (EditText) findViewById(R.id.writeMessageEditText);
    mSendChatMessageButton = (ImageButton) findViewById(R.id.sendChatMessageButton);
    mSendChatMessageButton.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View view) {
            if (mCurrentChannel != null) {
              String messageBody = mWriteMessageEditText.getText().toString();

              SendMessageTask sendTask = new SendMessageTask(messageBody);
              sendTask.execute((Void) null);
            }
          }
        });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle =
        new ActionBarDrawerToggle(
            this,
            drawer,
            toolbar,
            R.string.navigation_drawer_open,
            R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    mNavigationView = (NavigationView) findViewById(R.id.nav_view);
    mNavigationView.setNavigationItemSelectedListener(this);

    TextView nicknameTV = (TextView) mNavigationView.getHeaderView(0).findViewById(R.id.nickname);
    nicknameTV.setText(mIdentity);

    // Initialize chat
    mMembers = new ConcurrentHashMap<>();

    String twilioToken = intent.getStringExtra(ApplicationConstants.Extra.TWILIO_TOKEN);
    retrieveAccessTokenFromServer(twilioToken);
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_chat);

    if (MMX.getCurrentUser() == null) {
      MMX.unregisterListener(mEventListener);
      MMX.logout(null);
      Intent intent = new Intent(ChatActivity.this, LoginActivity.class);
      startActivity(intent);
    }

    mUser = getIntent().getParcelableExtra("User");

    MMX.registerListener(mEventListener);
    S3UploadService.init(this);
    mGPS = new GPSTracker(this);

    ActionBar ab = getActionBar();
    if (ab != null) {
      ab.setTitle("Chatting With: " + mUser.getUsername());
    }

    rvMessages = (RecyclerView) findViewById(R.id.rvMessages);
    etMessage = (EditText) findViewById(R.id.etMessage);
    btnSendText = (ImageButton) findViewById(R.id.btnSendText);
    btnSendPicture = (ImageButton) findViewById(R.id.btnSendPicture);
    btnSendLocation = (ImageButton) findViewById(R.id.btnSendLocation);
    btnSendVideo = (ImageButton) findViewById(R.id.btnSendVideo);

    messageList = new ArrayList<>();
    adapter = new MessageRecyclerViewAdapter(this, messageList);

    rvMessages.setAdapter(new SlideInBottomAnimationAdapter(adapter));
    final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
    layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    layoutManager.setStackFromEnd(true);
    layoutManager.setReverseLayout(false);
    rvMessages.setLayoutManager(layoutManager);

    etMessage.setOnKeyListener(
        new View.OnKeyListener() {
          public boolean onKey(View v, int keyCode, KeyEvent event) {
            if ((event.getAction() == KeyEvent.ACTION_DOWN)
                && (keyCode == KeyEvent.KEYCODE_ENTER)) {
              sendMessage();
              return true;
            }
            return false;
          }
        });

    btnSendText.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            sendMessage();
          }
        });

    btnSendPicture.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            selectImage();
          }
        });

    btnSendLocation.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            sendLocation();
          }
        });

    btnSendVideo.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            selectVideo();
          }
        });
  }
  private void init(View view) {
    ((TextView) view.findViewById(R.id.text_view_stats_fragment_title))
        .setText(Player.getInstance().getName() + "'s Stats");
    RecyclerView recycler = (RecyclerView) view.findViewById(R.id.recycler_view_stats_game);
    recycler.setLayoutManager(new LinearLayoutManager(getContext()));
    mAdapter =
        new FirebaseRecyclerAdapter<String, GameStatsViewHolder>(
            String.class,
            R.layout.card_game_stats,
            GameStatsViewHolder.class,
            LaserTagApplication.firebaseReference
                .child("users")
                .child(LaserTagApplication.getUid())
                .child("previousGames")) {

          @Override
          public void populateViewHolder(
              final GameStatsViewHolder holder, final String gameKey, final int position) {
            LaserTagApplication.firebaseReference
                .child("finishedGames")
                .child(gameKey)
                .addListenerForSingleValueEvent(
                    new ValueEventListener() {
                      @Override
                      public void onDataChange(DataSnapshot dataSnapshot) {
                        final DBGame dbGame = dataSnapshot.getValue(DBGame.class);
                        if (dbGame != null) {
                          holder.gameName.setText(
                              dbGame.getHost() + "'s " + dbGame.getGameType().toString());
                          DateFormat dateFormat = new SimpleDateFormat("MM/dd/yy");
                          holder.gameDate.setText(dateFormat.format(dbGame.getDate()));
                          DBPlayer dbPlayer =
                              dbGame
                                  .findPlayer(Player.getInstance().getName())
                                  .getPlayers()
                                  .get(Player.getInstance().getName());
                          holder.playerScore.setText(
                              "Score: " + dbPlayer.getPlayerStats().getScore());
                          holder.playerKD.setText(
                              "KD: "
                                  + dbPlayer.getPlayerStats().getKills()
                                  + " / "
                                  + dbPlayer.getPlayerStats().getDeaths());
                          holder.playerHP.setText(
                              "HP: "
                                  + String.format(
                                      "%.2f", dbPlayer.getPlayerStats().getHitPercentage() * 100)
                                  + "%");
                          holder.playerStatsView.setBackgroundColor(
                              Color.HSVToColor(136, dbPlayer.getPlayerStats().getColor()));

                          holder.itemView.setOnClickListener(
                              new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                  StatsDialogFragment dialog = new StatsDialogFragment();
                                  dialog.setDBGame(dbGame, gameKey);
                                  dialog.show(
                                      getActivity().getSupportFragmentManager(),
                                      "stats_dialog_fragment");
                                }
                              });
                        }
                      }

                      @Override
                      public void onCancelled(FirebaseError firebaseError) {}
                    });
          }
        };
    LinearLayoutManager manager = new LinearLayoutManager(getContext());
    manager.setReverseLayout(true);
    manager.setStackFromEnd(true);
    recycler.setLayoutManager(manager);
    recycler.setAdapter(mAdapter);
  }