Example usage for android.text TextWatcher TextWatcher

List of usage examples for android.text TextWatcher TextWatcher

Introduction

In this page you can find the example usage for android.text TextWatcher TextWatcher.

Prototype

TextWatcher

Source Link

Usage

From source file:com.example.feedback.ActivityFeedback.java

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

    // Set action bar title to Feedback.
    actionBar = getActionBar();//from  w w  w .  jav a  2  s . co m
    actionBar.setTitle(getResources().getString(R.string.title_feedback));

    // Set views.
    spinnerFrom = (Spinner) findViewById(R.id.spinner_from);
    inputText = (EditText) findViewById(R.id.input_test);
    checkScreen = (CheckBox) findViewById(R.id.check_screen);
    layoutScreen = (LinearLayout) findViewById(R.id.layout_screen);
    imageCrop = (ImageView) findViewById(R.id.image_crop);
    textPreview = (TextView) findViewById(R.id.text_preview);

    // Get screenshot from previous activity.
    getScreen();

    // Get device account(s) for spinner (select primary by default).
    getAccounts();
    spinnerFrom.setAdapter(accountAdapter);
    spinnerFrom.setSelection(1);

    // Set feedback to include screenshot/logs by default.
    checkScreen.setChecked(true);

    // Set text listener for feedback text.
    inputText.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(Editable s) {
        }

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

        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (s.length() > 0) {
                menuActionBar.findItem(R.id.action_send_disabled).setVisible(false);
                menuActionBar.findItem(R.id.action_send_enabled).setVisible(true);
            } else {
                menuActionBar.findItem(R.id.action_send_disabled).setVisible(true);
                menuActionBar.findItem(R.id.action_send_enabled).setVisible(false);
            }
        }
    });

    // Set click listener for checkbox.
    checkScreen.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (checkScreen.isChecked()) {
                layoutScreen.setVisibility(View.VISIBLE);
            } else {
                layoutScreen.setVisibility(View.INVISIBLE);
            }
        }
    });

    // Set click listener for screenshot image.
    imageCrop.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            displayScreen();
        }
    });
}

From source file:com.kerkr.edu.editView.FloatLabelLayout.java

private void setEditText(EditText editText) {
    // If we already have an EditText, throw an exception
    if (mEditText != null) {
        throw new IllegalArgumentException("We already have an EditText, can only have one");
    }/*from  w ww  . j a  v  a 2  s  .c o m*/
    mEditText = editText;

    // Update the label visibility with no animation
    updateLabelVisibility(false);

    mEditText.setOnFocusChangeListener(new OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            // TODO Auto-generated method stub

        }
    });
    // Add a TextWatcher so that we know when the text input has changed
    mEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void afterTextChanged(Editable s) {
            updateLabelVisibility(true);
        }

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

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    });

    // Add focus listener to the EditText so that we can notify the label that it is activated.
    // Allows the use of a ColorStateList for the text color on the label
    mEditText.setOnFocusChangeListener(new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean focused) {
            updateLabelVisibility(true);
        }
    });

    // If we do not have a valid hint, try and retrieve it from the EditText
    if (TextUtils.isEmpty(mHint)) {
        setHint(mEditText.getHint());
    }
}

From source file:com.google.samples.apps.topeka.fragment.SignInFragment.java

private void initContentViews(View view) {
    TextWatcher textWatcher = new TextWatcher() {
        @Override//from  w  w  w.  j a v  a2s  . c  om
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            /* no-op */
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // hiding the floating action button if text is empty
            if (s.length() == 0) {
                mDoneFab.hide();
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
            // showing the floating action button if avatar is selected and input data is valid
            if (isAvatarSelected() && isInputDataValid()) {
                mDoneFab.show();
            }
        }
    };

    mFirstName = (EditText) view.findViewById(R.id.first_name);
    mFirstName.addTextChangedListener(textWatcher);
    mLastInitial = (EditText) view.findViewById(R.id.last_initial);
    mLastInitial.addTextChangedListener(textWatcher);
    mDoneFab = (FloatingActionButton) view.findViewById(R.id.done);
    mDoneFab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.done:
                savePlayer(getActivity());
                removeDoneFab(new Runnable() {
                    @Override
                    public void run() {
                        if (null == mSelectedAvatarView) {
                            performSignInWithTransition(mAvatarGrid.getChildAt(mSelectedAvatar.ordinal()));
                        } else {
                            performSignInWithTransition(mSelectedAvatarView);
                        }
                    }
                });
                break;
            default:
                throw new UnsupportedOperationException("The onClick method has not been implemented for "
                        + getResources().getResourceEntryName(v.getId()));
            }
        }
    });
}

From source file:com.bloodtolife.bloodapp.CommentsFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_comments, container, false);
    db = new SQLiteHandler(getActivity());

    RecyclerView mCommentsView = (RecyclerView) rootView.findViewById(R.id.comment_list);
    mEditText = (EditText) rootView.findViewById(R.id.editText);
    final Button sendButton = (Button) rootView.findViewById(R.id.send_comment);

    final DatabaseReference commentsRef = FirebaseUtil.getCommentsRef().child(mPostRef);
    mAdapter = new FirebaseRecyclerAdapter<Comment, CommentViewHolder>(Comment.class, R.layout.comment_item,
            CommentViewHolder.class, commentsRef) {
        @Override//ww  w  .  j  ava 2s  . c  o  m
        protected void populateViewHolder(final CommentViewHolder viewHolder, Comment comment, int position) {
            user_ = db.getUserDetails();
            viewHolder.commentAuthor.setText(user_.get("name"));
            GlideUtil.loadProfileIcon(user_.get("profile_pic_url"), viewHolder.commentPhoto);

            viewHolder.authorRef = user_.get("uid");
            viewHolder.commentTime.setText(DateUtils.getRelativeTimeSpanString((long) comment.getTimestamp()));
            viewHolder.commentText.setText(comment.getText());
        }
    };
    sendButton.setEnabled(false);
    mEditText.setHint(R.string.new_comment_hint);
    mEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(DEFAULT_MSG_LENGTH_LIMIT) });
    mEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (editable.length() > 0) {
                sendButton.setEnabled(true);
            } else {
                sendButton.setEnabled(false);
            }
        }
    });
    sendButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Clear input box and hide keyboard.
            final Editable commentText = mEditText.getText();
            mEditText.setText("");
            InputMethodManager inputManager = (InputMethodManager) getActivity()
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.hideSoftInputFromWindow(mEditText.getWindowToken(),
                    InputMethodManager.HIDE_NOT_ALWAYS);

            FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
            if (user == null) {
                Toast.makeText(getActivity(), R.string.user_logged_out_error, Toast.LENGTH_SHORT).show();
            }

            Comment comment = new Comment(user.getDisplayName(), commentText.toString(), ServerValue.TIMESTAMP);
            commentsRef.push().setValue(comment, new DatabaseReference.CompletionListener() {
                @Override
                public void onComplete(DatabaseError error, DatabaseReference firebase) {
                    if (error != null) {
                        Log.w(TAG, "Error posting comment: " + error.getMessage());
                        Toast.makeText(getActivity(), "Error posting comment.", Toast.LENGTH_SHORT).show();
                        mEditText.setText(commentText);
                    }
                }
            });
        }
    });
    mCommentsView.setLayoutManager(new LinearLayoutManager(getActivity()));
    mCommentsView.setAdapter(mAdapter);
    return rootView;
}

From source file:com.jins_meme.bridge.OSCConfigFragment.java

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    handler = new Handler();

    layout = (LinearLayout) view.findViewById(R.id.osc_layout);
    layout.setOnTouchListener(new OnTouchListener() {
        @Override/* w ww .  j a va 2 s. com*/
        public boolean onTouch(View view, MotionEvent motionEvent) {
            Log.d("DEBUG", "view touch.");

            layout.requestFocus();

            return false;
        }
    });

    InputFilter[] filters = new InputFilter[1];
    filters[0] = new InputFilter() {
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart,
                int dend) {
            if (end > start) {
                String destTxt = dest.toString();
                String resultingTxt = destTxt.substring(0, dstart) + source.subSequence(start, end)
                        + destTxt.substring(dend);
                if (!resultingTxt
                        .matches("^\\d{1,3}(\\." + "(\\d{1,3}(\\.(\\d{1,3}(\\.(\\d{1,3})?)?)?)?)?)?")) {
                    return "";
                } else {
                    String[] splits = resultingTxt.split("\\.");
                    for (String split : splits) {
                        if (Integer.valueOf(split) > 255) {
                            return "";
                        }
                    }
                }
            }
            return null;
        }
    };

    etRemoteIP = (EditText) view.findViewById(R.id.remote_ip);
    String savedRemoteIP = ((MainActivity) getActivity()).getSavedValue("REMOTE_IP", "255.255.255.255");
    if (savedRemoteIP.equals("255.255.255.255")) {
        etRemoteIP.setText(MemeOSC.getRemoteIPv4Address());
    } else {
        etRemoteIP.setText(savedRemoteIP);
    }
    etRemoteIP.setFilters(filters);
    etRemoteIP.setOnFocusChangeListener(new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean b) {
            if (!b) {
                InputMethodManager imm = (InputMethodManager) getActivity()
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    });
    etRemoteIP.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            Log.d("DEBUG", "after text changed " + editable.toString());

            ((MainActivity) getActivity()).autoSaveValue("REMOTE_IP", editable.toString());

            testOSC.setRemoteIP(etRemoteIP.getText().toString());
            testOSC.initSocket();
        }
    });

    etRemotePort = (EditText) view.findViewById(R.id.remote_port);
    etRemotePort.setText(String.valueOf(((MainActivity) getActivity()).getSavedValue("REMOTE_PORT", 10316)));
    etRemotePort.setOnFocusChangeListener(new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean b) {
            if (!b) {
                InputMethodManager imm = (InputMethodManager) getActivity()
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    });
    etRemotePort.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            Log.d("DEBUG", "after text changed " + editable.toString());

            if (editable.toString().length() > 0) {
                ((MainActivity) getActivity()).autoSaveValue("REMOTE_PORT",
                        Integer.valueOf(editable.toString()));

                testOSC.setRemotePort(Integer.parseInt(editable.toString()));
                testOSC.initSocket();
            }
        }
    });

    etHostIP = (EditText) view.findViewById(R.id.host_ip);
    etHostIP.setText(MemeOSC.getHostIPv4Address());
    etHostIP.setEnabled(false);

    etHostPort = (EditText) view.findViewById(R.id.host_port);
    etHostPort.setText(String.valueOf(((MainActivity) getActivity()).getSavedValue("HOST_PORT", 11316)));
    etHostPort.setOnFocusChangeListener(new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean b) {
            if (!b) {
                InputMethodManager imm = (InputMethodManager) getActivity()
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    });
    etHostPort.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            Log.d("DEBUG", "after text changed " + editable.toString());

            if (editable.toString().length() > 0) {
                ((MainActivity) getActivity()).autoSaveValue("HOST_PORT", Integer.valueOf(editable.toString()));
                testOSC.setHostPort(Integer.parseInt(editable.toString()));
                testOSC.initSocket();
            }
        }
    });

    btnTest = (Button) view.findViewById(R.id.remote_test);
    btnTest.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            layout.requestFocus();

            testOSC.setAddress("/meme/bridge", "/test");
            testOSC.setTypeTag("si");
            testOSC.addArgument(etRemoteIP.getText().toString());
            testOSC.addArgument(Integer.parseInt(etRemotePort.getText().toString()));
            testOSC.flushMessage();
        }
    });

    testOSC = new MemeOSC();
    testOSC.setRemoteIP(etRemoteIP.getText().toString());
    testOSC.setRemotePort(Integer.parseInt(etRemotePort.getText().toString()));
    testOSC.setHostPort(Integer.parseInt(etHostPort.getText().toString()));
    testOSC.initSocket();

    isShown = true;
    Thread rcvTestThread = new Thread(new ReceiveTestTRunnable());
    rcvTestThread.start();
}

From source file:com.example.nitish.welcomapp.activitypt.ElementListFragment.java

/**
 * Setup the listener for the filtering TextView.
 *///from ww  w . j a v a  2  s.com
private void setupFilter() {
    final EditText filterEditText = (EditText) getActivity().findViewById(R.id.filter);
    filterEditText.addTextChangedListener(new TextWatcher() {
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        public void afterTextChanged(Editable s) {
            mFilter = s.toString();
            mAdapter.getFilter().filter(mFilter);
        }
    });
}

From source file:com.justplay1.shoppist.features.search.SearchFragment.java

@Override
protected void init(View view) {
    adapter = new SearchAdapter(getContext(), contextType);
    adapter.setClickListener(this);

    searchView.setAdapter(adapter);/*from  ww  w  . ja  v  a2 s .c  o  m*/
    updateNavigationIcon();
    searchView.showIcon(true);
    searchView.setOnIconClickListener(this);
    searchView.setOnSearchListener(this);
    searchView.setOnMenuItemClickListener(this);
    searchView.setOnSearchFocusChangedListener(this);
    searchView.setOnContainerTouchClickListener(this);
    searchView.setText(null);
    searchView.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence query, int start, int before, int count) {
            showVoiceButton(query.length() == 0 && searchView.isActivated());
            showClearButton(query.length() > 0 && searchView.isActivated());
            search(query.toString());
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
    searchView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
        @Override
        public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop,
                int oldRight, int oldBottom) {
            searchView.removeOnLayoutChangeListener(this);
            searchView.setActivated(true);
            presenter.attachView(SearchFragment.this);
        }
    });
    searchView.setHint(getString(R.string.search));
}

From source file:com.meetingninja.csse.agenda.AgendaItemAdapter.java

@Override
public LinearLayout updateView(final View view, final TreeNodeInfo<Topic> treeNodeInfo) {

    final LinearLayout rowView = (LinearLayout) view;

    final Topic rowTopic = treeNodeInfo.getId();

    // System.out.println("Echo: Checked" + rowTopic + " " + counter + " "
    // + Comparison.size() + " " + checked);

    final EditText mTitle = (EditText) rowView.findViewById(R.id.agenda_edit_topic);

    final TextView mTime = (TextView) rowView.findViewById(R.id.agenda_topic_time);
    if (textHandlers.containsKey(mTitle)) {
        mTitle.removeTextChangedListener(textHandlers.get(mTitle));
    }// w  w w. j  a  va  2  s.co  m
    mTitle.setText(rowTopic.getTitle());

    // System.out.println("Echo: Here" + rowTopic.getTitle() + " " +
    // rowView);

    TextWatcher c = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String text = s.toString();

            // rowTopic.setTitle(text);
            mTitle.setTag(text);
            rowTopic.setTitle(text);

            Log.d(TAG, "Text changed" + treeNodeInfo.getLevel() + " " + treeNodeInfo.getId());
            manager.getChildren(treeNodeInfo.getId());

        }

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

        @Override
        public void afterTextChanged(Editable s) {

        }
    };

    mTitle.addTextChangedListener(c);
    textHandlers.put(mTitle, c);

    final Button mAddTopicBtn = (Button) rowView.findViewById(R.id.agenda_subtopicAddBtn);
    final Button mTimeBtn = (Button) rowView.findViewById(R.id.agenda_topicTimeBtn);
    System.out.println();

    // Add SubTopic Button
    // mAddTopicBtn.setTag(rowTopic);
    mAddTopicBtn.setOnClickListener(new SubTopicListener(rowTopic));

    // Set Time Button
    mTimeBtn.setTag(rowTopic);
    mTimeBtn.setOnClickListener(new OnTimeBtnClick(rowTopic, mTime));

    Map<String, String> info = getDescription(rowTopic);

    String time = info.containsKey("time") ? info.get("time") : "";
    time = "(" + rowTopic.getTime() + "m)";
    mTime.setText(time);

    // If a topic has subTopics, then its time is determined by the sum of
    // the subTopics
    if (getManager().getChildren(rowTopic).size() != 0) {
        // mTimeBtn.setVisibility(View.GONE);
        mTime.setVisibility(View.GONE);
        mTimeBtn.setVisibility(View.GONE);
    } else {
        mTime.setVisibility(View.VISIBLE);
        mTimeBtn.setVisibility(View.VISIBLE);
        // timeBtn.setChecked(selected.contains(treeNodeInfo.getId()));
    }
    getManager().notifyDataSetChanged();
    return rowView;
}

From source file:com.example.naveen.dentalorder.ui.CustomerInfoFragment.java

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    mDrNameView.addTextChangedListener(new TextWatcher() {
        @Override//from   www.j  av  a 2  s.  c o m
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            mPage.getData().putString(CustomerInfoPage.DR_NAME_DATA_KEY,
                    (editable != null) ? editable.toString() : null);
            mPage.notifyDataChanged();
        }
    });

    mNameView.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            mPage.getData().putString(CustomerInfoPage.NAME_DATA_KEY,
                    (editable != null) ? editable.toString() : null);
            mPage.notifyDataChanged();
        }
    });

    mAgeView.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            mPage.getData().putString(CustomerInfoPage.AGE_DATA_KEY,
                    (editable != null) ? editable.toString() : null);
            mPage.notifyDataChanged();
        }
    });

    mDateSend.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            mPage.getData().putString(CustomerInfoPage.DATE_SEND_DATA_KEY,
                    (editable != null) ? editable.toString() : null);
            mPage.notifyDataChanged();
        }
    });

    mDateRequired.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            mPage.getData().putString(CustomerInfoPage.DATE_REQ_DATA_KEY,
                    (editable != null) ? editable.toString() : null);
            mPage.notifyDataChanged();
        }
    });

    mMale.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            mPage.getData().putString(CustomerInfoPage.SEX_DATA_KEY, (isChecked ? "Male" : "Female"));
            mPage.notifyDataChanged();
        }
    });

    mFemale.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            mPage.getData().putString(CustomerInfoPage.SEX_DATA_KEY, (isChecked ? "Female" : "Male"));
            mPage.notifyDataChanged();
        }
    });
}

From source file:com.google.firebase.codelab.friendlychat.ui.messages.MessagesActivity.java

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

    // Initialize ProgressBar and RecyclerView.
    mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
    mMessageRecyclerView = (RecyclerView) findViewById(R.id.messageRecyclerView);
    mLinearLayoutManager = new LinearLayoutManager(this);
    mLinearLayoutManager.setStackFromEnd(true);
    mMessageRecyclerView.setLayoutManager(mLinearLayoutManager);

    FirebaseDatabase.getInstance().setPersistenceEnabled(true);

    mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference();
    mFirebaseAdapter = new FirebaseRecyclerAdapter<FriendlyMessage, MessageViewHolder>(FriendlyMessage.class,
            R.layout.item_message, MessageViewHolder.class, mFirebaseDatabaseReference.child(MESSAGES_CHILD)) {

        @Override//w  w  w  .j  a va 2  s  .co  m
        protected void populateViewHolder(MessageViewHolder viewHolder, FriendlyMessage friendlyMessage,
                int position) {
            mProgressBar.setVisibility(ProgressBar.INVISIBLE);
            viewHolder.bind(friendlyMessage);
        }
    };

    mFirebaseAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
        @Override
        public void onItemRangeInserted(int positionStart, int itemCount) {
            super.onItemRangeInserted(positionStart, itemCount);
            int friendlyMessageCount = mFirebaseAdapter.getItemCount();
            int lastVisiblePosition = mLinearLayoutManager.findLastCompletelyVisibleItemPosition();
            // If the recycler view is initially being loaded or the
            // user is at the bottom of the list, scroll to the bottom
            // of the list to show the newly added message.
            if (lastVisiblePosition == -1 || (positionStart >= (friendlyMessageCount - 1)
                    && lastVisiblePosition == (positionStart - 1))) {
                mMessageRecyclerView.scrollToPosition(positionStart);
            }
        }
    });

    mMessageRecyclerView.setLayoutManager(mLinearLayoutManager);
    mMessageRecyclerView.setAdapter(mFirebaseAdapter);

    mMessageEditText = (EditText) findViewById(R.id.messageEditText);

    mMessageEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            if (charSequence.toString().trim().length() > 0) {
                mSendButton.setEnabled(true);
            } else {
                mSendButton.setEnabled(false);
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {
        }
    });

    mSendButton = (Button) findViewById(R.id.sendButton);
    mSendButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            FriendlyMessage friendlyMessage = new FriendlyMessage(mMessageEditText.getText().toString(),
                    mUsername, mPhotoUrl);
            mFirebaseDatabaseReference.child(MESSAGES_CHILD).push().setValue(friendlyMessage);
            mMessageEditText.setText("");
        }
    });

}