Saya mencoba membuat aplikasi Notepad ini menggunakan Komponen Arsitektur Android Jetpack LiveData, ViewModel, Room, dan DataBinding. Aplikasi ini berisi tiga tata letak aktivitas, tata letak menu, tata letak bilah alat yang saya rencanakan untuk digunakan untuk semua aktivitas ini. Tata letak toolbar ini berisi textView yang akan digunakan untuk mengatur tata letak toolbar menggunakan DataBinding.

Berikut ini adalah file XML penting:

custom_notes_toolbar_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data>

        <variable
            name="toolbarTitle"
            type="String" />
    </data>

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/activity_toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/color_primary">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:fontFamily="@font/nunito_semibold"
            android:text="@{toolbarTitle}"
            android:textColor="@color/muted_white"
            android:textSize="20sp" />

    </androidx.appcompat.widget.Toolbar>

</layout>

activity_display_note.xml

    <?xml version="1.0" encoding="utf-8"?>
    <layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:bind="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        tools:context=".view.DisplayNoteActivity">
    
        <data>
    
            <variable
                name="toolbarTitle"
                type="String" />
        </data>
    
        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
    
            <LinearLayout
                android:id="@+id/toolbar_linear_layout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent">
    
                <com.google.android.material.appbar.AppBarLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">
    
                    <include
                        android:id="@+id/toolbar"
                        layout="@layout/custom_notes_toolbar_layout"
                        bind:toolbarTitle="@{toolbarTitle}" />
    
                </com.google.android.material.appbar.AppBarLayout>
    
            </LinearLayout>
    
            <TextView
                android:id="@+id/title_text_view"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fontFamily="@font/nunito"
                android:padding="15dp"
                android:textSize="25sp"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@id/toolbar_linear_layout" />
    
            <TextView
                android:id="@+id/content_text_view"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:fontFamily="@font/nunito_extralight"
                android:gravity="start"
                android:padding="15dp"
                android:textSize="20sp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@id/title_text_view" />
    
            <com.google.android.material.floatingactionbutton.FloatingActionButton
                android:id="@+id/edit_note_floating_action_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginEnd="30sp"
                android:layout_marginBottom="30sp"
                android:contentDescription="@string/edit_note"
                android:src="@drawable/ic_edit"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent" />
    
        </androidx.constraintlayout.widget.ConstraintLayout>
    </layout>

display_note_menu.xml

<?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">
    
        <item
            android:id="@+id/delete_menu_option"
            android:icon="@drawable/ic_delete"
            android:title="@string/delete_menu_string"
            app:showAsAction="always" />
    
    </menu>

DisplayNoteActivity.java

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.arpansircar.java.notepadapplicationusingmvvm.R;
import com.arpansircar.java.notepadapplicationusingmvvm.databinding.ActivityDisplayNoteBinding;
import com.arpansircar.java.notepadapplicationusingmvvm.model.Constants;
import com.arpansircar.java.notepadapplicationusingmvvm.room.NotesEntity;
import com.arpansircar.java.notepadapplicationusingmvvm.viewmodel.DisplayNoteActivityViewModel;

/**
 * The DisplayNoteActivity displays the contents of a single note.
 * Upon clicking a certain note in the NotesActivity RecyclerView, the user is guided to this activity and the selected note is displayed here.
 * In this activity, the user can view, delete, or update the particular note as required.
 * All such changes are reflected back in the NotesActivity.
 */
public class DisplayNoteActivity extends AppCompatActivity implements View.OnClickListener {

    private ActivityDisplayNoteBinding activityDisplayNoteBinding;
    private NotesEntity currentNoteEntity;
    private DisplayNoteActivityViewModel displayNoteActivityViewModel;

    /*The onCreate method is the first method to be executed when the application starts up.
     * Here, those methods are called that are to be executed only once.
     * This particular method executes the setToolbarMethod(), getIntentData(), and initializeViewModel() methods.
     * The setToolbarMethod() sets the toolbar which contains the functionality for deleting a note.
     * The getIntentData() fetches complete note details including the note id, title, content, and date.
     * The initializeViewModel() method creates an instance of the AddEditNoteActivityViewModel class.*/
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityDisplayNoteBinding = DataBindingUtil.setContentView(this, R.layout.activity_display_note);
        setToolbarMethod();
        getIntentData();
        initializeViewModel();
    }

    /*onStart() lifecycle callback method is executed after onCreate().
     * In this callback method, two methods are executed.
     * The setObserver() method activates the observer to check any changes arising within the LiveData object.
     * The setOnClickListenerMethod() intercepts any clicks occurring within the activity.*/
    @Override
    protected void onStart() {
        super.onStart();
        startObserver();
        setOnClickListenerMethod();
    }

    /*The onCreateOptionsMenu(...) creates the menu options in the toolbar.
     * Here, a single menu option is used to delete the note being viewed.*/
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.display_note_menu, menu);
        return true;
    }

    /*The onOptionsItemSelected(...) method intercepting the clicks occurring on the menu options.
     * Here, a single menu option will be displayed to allow the user to delete the particular note being viewed.
     * Upon being pressed, this delete option will trigger the deleteNoteMethod() and the activity will be removed from the view.*/
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.delete_menu_option) {
            deleteNoteMethod();
            finish();
            return true;
        } else {
            return super.onOptionsItemSelected(item);
        }
    }

    /*The setToolbarMethod() sets the custom toolbar in the activity.*/
    private void setToolbarMethod() {
        Toolbar toolbar = activityDisplayNoteBinding.toolbar.activityToolbar;
        activityDisplayNoteBinding.setToolbarTitle(getString(R.string.display_activity_title));
        setSupportActionBar(toolbar);
    }

    /*The initializeViewModel() creates an instance to the DisplayNoteActivityViewModel for communicating with the database.*/
    private void initializeViewModel() {
        displayNoteActivityViewModel = new ViewModelProvider(this).get(DisplayNoteActivityViewModel.class);
    }

    /*The setObserverMethod() method is used simply activates the observer.*/
    private void startObserver() {
        final Observer<NotesEntity> notesEntityObserver = notesEntity -> {
            this.currentNoteEntity = notesEntity;
            setNoteInActivity(notesEntity);
        };

        displayNoteActivityViewModel.selectNoteMethod(getIntentData()).observe(this, notesEntityObserver);
    }

    /*The setOnClickListenerMethod() method sets the onClickListener to the floating action button used in the activity.*/
    private void setOnClickListenerMethod() {
        activityDisplayNoteBinding.editNoteFloatingActionButton.setOnClickListener(this);
    }

    /*The setNoteInActivity(...) method sets the NotesEntity instance within the activity.
     * The method is triggered by any changes occurring within the LiveData instance.
     * A try-catch block is placed to handle the NullPointerExceptions that arise when a note is deleted.
     * The NullPointerException occurs as the observer observes a change and tries to fetch the changed note.
     * But this isn't possible as the note has already been deleted from the database, causing the exception.
     * Therefore, the catch block handles the exception by removing the activity from view and showing a Toast message.*/
    private void setNoteInActivity(NotesEntity notesEntity) {
        try {
            activityDisplayNoteBinding.titleTextView.setText(notesEntity.getTitle());
            activityDisplayNoteBinding.contentTextView.setText(notesEntity.getContent());
        } catch (NullPointerException nullPointerException) {
            finish();
        }
    }

    /*The getIntentData() method extracts the noteID from the intent.*/
    private int getIntentData() {
        Intent intent = getIntent();
        return intent.getIntExtra(Constants.COLUMN_ID, -1);
    }

    /*The deleteNoteMethod() deletes a note from the database and the NotesActivity.
     * The method is triggered by the onOptionsItemSelected() method when the user presses the delete menu option in the toolbar.*/
    private void deleteNoteMethod() {
        displayNoteActivityViewModel.deleteNoteMethod(currentNoteEntity);
        Toast.makeText(this, "Note Deleted", Toast.LENGTH_SHORT).show();
    }

    /*The onClick(...) method intercepts all clicks performed in the current activity.
     * When the floating action button is clicked, the "edit" function, note id, title, content, and date is bundled into the intent as extras.
     * Finally, this data is sent into the AddEditNoteActivity and the activity is started.*/
    @Override
    public void onClick(View view) {
        if (view == activityDisplayNoteBinding.editNoteFloatingActionButton) {
            Intent editNoteIntent = new Intent(DisplayNoteActivity.this, AddEditNoteActivity.class);
            editNoteIntent.putExtra("function", "edit");
            editNoteIntent.putExtra(Constants.COLUMN_ID, currentNoteEntity.getId());
            editNoteIntent.putExtra(Constants.COLUMN_NAME_TITLE, currentNoteEntity.getTitle());
            editNoteIntent.putExtra(Constants.COLUMN_NAME_CONTENT, currentNoteEntity.getContent());
            editNoteIntent.putExtra(Constants.COLUMN_NAME_DATE, currentNoteEntity.getDate());

            startActivity(editNoteIntent);
        }
    }
}

Sekarang, masalah muncul di setToolbarMethod():

private void setToolbarMethod() {
        Toolbar toolbar = activityDisplayNoteBinding.toolbar.activityToolbar;
        activityDisplayNoteBinding.setToolbarTitle(getString(R.string.display_activity_title));
        setSupportActionBar(toolbar);
    }

Ketika saya mencoba metode ini, itu menyebabkan dua judul Toolbar diatur, yaitu nama aplikasi dan judul yang saya coba atur melalui DataBinding.

enter image description here

Saya mencoba untuk menghapus setToolbarMethod() sepenuhnya, tetapi itu berarti saya tidak akan dapat mengatur Toolbar, pada dasarnya, saya juga tidak akan dapat mengatur menu. Dan alasan saya menggunakan DataBinding untuk mengatur judul bilah alat daripada menggunakan metode setTitle() yang disediakan adalah karena saya menginginkan font yang berbeda untuk teks judul daripada yang disediakan secara default oleh metode ini.

Saya tahu bahwa pertanyaan ini mungkin terdengar sedikit membingungkan. Jika diperlukan, saya dapat memberikan detail sesuai kebutuhan. Terima kasih atas bantuan apa pun.

0
Arpan Sircar 6 November 2020, 11:32

1 menjawab

Jawaban Terbaik

Mari kita membedah ini:

<androidx.appcompat.widget.Toolbar
    android:id="@+id/activity_toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/color_primary">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:fontFamily="@font/nunito_semibold"
        android:text="@{toolbarTitle}"
        android:textColor="@color/muted_white"
        android:textSize="20sp" />

</androidx.appcompat.widget.Toolbar>

Anda meletakkan TextView di bilah alat Anda, tetapi bilah alat sudah memiliki dukungan untuk judul. Hapus tampilan teks ini, jangan atur apa pun pada tampilan teks, cari tahu cara mengubah bilah alat!

private void setToolbarMethod() {
        Toolbar toolbar = activityDisplayNoteBinding.toolbar.activityToolbar;
        setSupportActionBar(toolbar);
    }

Ini sekarang akan membuat toolbar Anda.

Di AndroidManifest.xml Anda, Anda akan melihat sesuatu seperti ini:

  <activity
            android:name=".foo"
            android:label="some value" /> <-- you can change some value here to give the toolbar a default title.

Kalau tidak,

<androidx.appcompat.widget.Toolbar
    app:title="foo"
    android:id="@+id/activity_toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/color_primary">

Berbagai cara mengatur judul, masalah Anda pada dasarnya disebabkan oleh memiliki TextView di dalam bilah alat tanpa alasan

  private void setNoteInActivity(NotesEntity notesEntity) {
        try {
            activityDisplayNoteBinding.titleTextView.setText(notesEntity.getTitle()); <-- this now becomes invalid, the text view is removed
            activityDisplayNoteBinding.contentTextView.setText(notesEntity.getContent());
        } catch (NullPointerException nullPointerException) { <-- side-note, this is terrible and probably not what you want to be doing, you should at least be printing the stack trace, calling finish will kill the entire activity without you or the user knowing what happened
            finish();
        }
    }

Anda dapat menggunakan getSupportActionBar().setTitle("My Title"); sebagai gantinya

1
a_local_nobody 6 November 2020, 09:05