ua.boberproduction.bbr.notes.NoteEditorFragment.java Source code

Java tutorial

Introduction

Here is the source code for ua.boberproduction.bbr.notes.NoteEditorFragment.java

Source

/*
* Copyright 2015 Kostiantyn Aloshychev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package ua.boberproduction.bbr.notes;

import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import ua.boberproduction.bbr.MainActivity;
import ua.boberproduction.bbr.R;
import ua.boberproduction.bbr.sqlite.SQLiteNotebookRepository;

/**
 * Fragment containing a form for composing a custom note by the user.
 */
public class NoteEditorFragment extends Fragment implements NoteEditorContract.View {
    private NoteEditorPresenter noteEditorPresenter;
    private FloatingActionButton floatingActionButton;
    private EditText titleEdit;
    private EditText textEdit;
    private boolean editMode = false;
    private Note note;

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

        noteEditorPresenter = new NoteEditorPresenter(this, SQLiteNotebookRepository.getInstance());

        setHasOptionsMenu(true);
        setRetainInstance(true);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_add_note, container, false);
        titleEdit = (EditText) view.findViewById(R.id.edit_note_title);
        textEdit = (EditText) view.findViewById(R.id.edit_note_text);
        floatingActionButton = (FloatingActionButton) view.findViewById(R.id.save_note_btn);

        // check if fragment extras contain note id, which means fragment should work in edit mode and populate the text fields with data
        Bundle bundle = getArguments();
        if (bundle != null && bundle.containsKey(getString(R.string.tag_noteId))) {
            editMode = true;

            String title = bundle.getString(getString(R.string.notes_title));
            String text = bundle.getString(getString(R.string.notes_note_content));
            String articleId = bundle.getString(getString(R.string.tag_articleid));
            note = new Note(title, articleId, text);

            displayNoteForEditing(note);
        }

        setSaveBtnClickListener();

        return view;
    }

    private void setSaveBtnClickListener() {
        floatingActionButton.setOnClickListener(v -> {
            enableSaveButton(false);
            hideSoftKeyboard();
            // Save note only if text field is not empty.
            if (!textEdit.getText().toString().equals("")) {
                ((MainActivity) getActivity()).displayProgressbar(true);
                // Add entered note to notebook. If no noteId was included (!editMode), new note will be created (noteId==0)
                int noteId = 0;
                if (editMode) {
                    noteId = getArguments().getInt(getString(R.string.tag_noteId));
                }
                note = new Note(noteId, titleEdit.getText().toString(), "", textEdit.getText().toString());
                noteEditorPresenter.saveNote(note);
            } else {
                // if text field is empty, alert user and do nothing
                Toast.makeText(getActivity(), R.string.notes_toast_empty, Toast.LENGTH_SHORT).show();
                enableSaveButton(true);
            }
        });
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);

        // show the subtitle
        ActionBar actionbar = ((MainActivity) getActivity()).getSupportActionBar();
        if (actionbar != null) {
            if (editMode) {
                actionbar.setSubtitle(getString(R.string.action_edit_note));
            } else
                actionbar.setSubtitle(getString(R.string.action_write_note));
        }
    }

    private void hideSoftKeyboard() {
        View view = getActivity().getCurrentFocus();
        if (view != null) {
            InputMethodManager imm = (InputMethodManager) getActivity()
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    private void enableSaveButton(boolean enable) {
        if (floatingActionButton != null) {
            if (enable) {
                floatingActionButton.setEnabled(true);
                floatingActionButton.setBackgroundTintList(
                        ColorStateList.valueOf(ContextCompat.getColor(getActivity(), R.color.colorPrimary)));
            } else {
                floatingActionButton.setEnabled(false);
                floatingActionButton.setBackgroundTintList(
                        ColorStateList.valueOf(ContextCompat.getColor(getActivity(), R.color.save_btn_disabled)));
            }
        }
    }

    @Override
    public void displayNoteForEditing(Note note) {
        titleEdit.setText(note.getTitle());
        textEdit.setText(note.getText());
    }

    @Override
    public void displayProgressbar(boolean show) {
        ProgressBar progressBar = (ProgressBar) getActivity().findViewById(R.id.progressBar);
        if (show)
            progressBar.setVisibility(View.VISIBLE);
        else
            progressBar.setVisibility(View.GONE);
    }

    @Override
    public void showNote() {
        // put data into bundle
        Bundle bundle = new Bundle();
        bundle.putInt(getString(R.string.tag_noteId), note.getId());
        bundle.putString(getString(R.string.tag_articleid), note.getArticleId());
        bundle.putString(getString(R.string.notes_title), note.getTitle());
        bundle.putString(getString(R.string.notes_note_content), note.getText());
        // create and display fragment
        Fragment fragment = new NoteViewerFragment();
        fragment.setArguments(bundle);
        FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
        ft.setCustomAnimations(R.animator.slide_in_right, R.animator.slide_out_left, R.animator.slide_in_left,
                R.animator.slide_out_right);
        ft.replace(R.id.main_frame, fragment, getString(R.string.tag_content_fragment)).addToBackStack("edit")
                .commit();
    }

}