当我尝试为活动设置工具栏时,会设置两个工具栏标题需要有关删除其中之一的帮助

如何解决当我尝试为活动设置工具栏时,会设置两个工具栏标题需要有关删除其中之一的帮助

我试图使用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设置的标题。

enter image description here

我试图完全删除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 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-