如何解决当我尝试为活动设置工具栏时,会设置两个工具栏标题需要有关删除其中之一的帮助
我试图使用LiveData,ViewModel,Room和DataBinding的Android Jetpack体系结构组件制作此记事本应用程序。该应用程序包含三个活动布局,一个菜单布局,一个我打算用于所有这些活动的工具栏布局。该工具栏布局包含一个textView,它将用于使用DataBinding设置工具栏布局。
以下是重要的XML文件:
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,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);
}
}
}
现在,在setToolbarMethod()中出现问题:
private void setToolbarMethod() {
Toolbar toolbar = activityDisplayNoteBinding.toolbar.activityToolbar;
activityDisplayNoteBinding.setToolbarTitle(getString(R.string.display_activity_title));
setSupportActionBar(toolbar);
}
当我尝试此方法时,它将导致设置两个工具栏标题,即应用程序的名称和我要通过DataBinding设置的标题。
我试图完全删除setToolbarMethod(),但这意味着我将无法设置工具栏,实际上,我也将无法设置菜单。我之所以使用DataBinding来设置工具栏标题而不是使用提供的setTitle()方法,是因为我想要的标题文本字体与该方法默认提供的字体不同。
我知道这个问题听起来有些混乱。如果需要,我可以根据需要提供详细信息。感谢您的帮助。
解决方法
让我们对此进行剖析:
<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>
您正在将TextView放入工具栏,但是工具栏已经支持标题。删除此textview,不要在textview上设置任何内容,找出如何更改工具栏!
private void setToolbarMethod() {
Toolbar toolbar = activityDisplayNoteBinding.toolbar.activityToolbar;
setSupportActionBar(toolbar);
}
现在将创建您的工具栏。
在您的AndroidManifest.xml中,您将看到以下内容:
<activity
android:name=".foo"
android:label="some value" /> <-- you can change some value here to give the toolbar a default title.
或者,
<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">
设置标题的各种方法不同,基本上是由于无缘无故地在工具栏中使用TextView引起的
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();
}
}
您可以改用getSupportActionBar().setTitle("My Title");
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。