工具栏中未显示菜单项

toiithl6  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(465)

我有工具栏,我想显示两个菜单图标,即myicon\u clearnifications和/myicon\u goback,但当我单击“仅通知”时,工具栏上不会显示这两个菜单项。其他内容会显示,但工具栏甚至不会显示。
xml工具栏代码

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorWhite"
    tools:context="Activities.AllNotifications">

    <androidx.appcompat.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:id="@+id/allNotifications_tollbar"
        android:layout_alignParentTop="true"
        android:background="#5A6E64"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"

        />

    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="2dp"
        android:id="@+id/allNotifications_RecyclerView"/>

</RelativeLayout>

我的菜单项代码

<?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/allNotifications_item_clear"
        android:title="CLEAR"
        android:icon="@drawable/myicon_clearnotifications"
        android:checkable="true"
        app:showAsAction="always"
        />

    <item
        android:id="@+id/allNotifications_item_goBack"
        android:title="GO BACK"
        android:icon="@drawable/myicon_goback"
        android:checkable="true"
        app:showAsAction="always"
        />
</menu>

这是我的java代码

package Activities;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;

import com.example.connectsocialmediaapp.R;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import com.google.firebase.firestore.WriteBatch;

import java.util.ArrayList;

import AdapterClasses.AllNotificationsAdapter;
import ModelClasses.Model_AllNotifications;

public class AllNotifications extends AppCompatActivity {

    private FirebaseFirestore objectFirebaseFirestore;
    private RecyclerView objectRecyclerView;

    private AllNotificationsAdapter objectAllNotificationsAdapter;
    private Toolbar objectToolbar;

    private FirebaseAuth objectFirebaseAuth;
    private Dialog objectDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_all_notifications);

        objectFirebaseFirestore=FirebaseFirestore.getInstance();
        objectFirebaseAuth=FirebaseAuth.getInstance();

        attachJavaToXML();
        getAllNotificationIntoRV();
    }

    @Override
    protected void onStart() {
        super.onStart();
        objectAllNotificationsAdapter.startListening();
    }

    @Override
    protected void onStop() {
        super.onStop();
        objectAllNotificationsAdapter.stopListening();
    }

    private void getAllNotificationIntoRV()
    {
        try
        {
            if(objectFirebaseAuth!=null) {
                String currentLoggedInUser = objectFirebaseAuth.getCurrentUser().getEmail();
                Query objectQuery = objectFirebaseFirestore.collection("userProfileData")
                        .document(currentLoggedInUser).collection("Notifications");

                FirestoreRecyclerOptions<Model_AllNotifications> objectOptions =
                        new FirestoreRecyclerOptions.Builder<Model_AllNotifications>()
                                .setQuery(objectQuery, Model_AllNotifications.class).build();
                objectAllNotificationsAdapter = new AllNotificationsAdapter(objectOptions);
                objectRecyclerView.setAdapter(objectAllNotificationsAdapter);

                objectRecyclerView.setLayoutManager(new LinearLayoutManager(this));
            }
                else
                {
                    Toast.makeText(this, R.string.no_user_online, Toast.LENGTH_SHORT).show();
                }

        }
        catch (Exception e)
        {
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    ArrayList<String> objectStringArrayList=new ArrayList<>();
    private void clearAllNotifications()
    {
        try
        {
            if(objectFirebaseAuth!=null)
            {
                final String currentLoggedInUser=objectFirebaseAuth.getCurrentUser().getEmail();
                objectFirebaseFirestore.collection("userProfileData")
                        .document(currentLoggedInUser)
                        .collection("Notifications")
                        .get()
                        .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                            @Override
                            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                                if(task.isSuccessful())
                                {
                                    for(QueryDocumentSnapshot objectQueryDocumentSnapshot:task.getResult())
                                    {
                                        objectStringArrayList.add(objectQueryDocumentSnapshot.getId());
                                        WriteBatch objectWriteBatch=objectFirebaseFirestore.batch();

                                        for(int count=0;count<objectStringArrayList.size();count++)
                                        {
                                            objectWriteBatch.delete(
                                                    objectFirebaseFirestore.collection("userProfileData")
                                                    .document(currentLoggedInUser)
                                                    .collection("Notifications")
                                                    .document(objectStringArrayList.get(count))
                                            );
                                        }
                                        objectWriteBatch.commit().addOnCompleteListener(new OnCompleteListener<Void>() {
                                            @Override
                                            public void onComplete(@NonNull Task<Void> task) {
                                                if(task.isSuccessful())
                                                {
                                                    Toast.makeText(AllNotifications.this, "Notifications Cleared", Toast.LENGTH_SHORT).show();
                                                }
                                                else if(!task.isSuccessful())
                                                {
                                                    Toast.makeText(AllNotifications.this, task.getException().toString(), Toast.LENGTH_SHORT).show();
                                                }
                                            }
                                        });
                                    }
                                }
                            }
                        });
            }
            else
            {
                Toast.makeText(this, R.string.no_user_online, Toast.LENGTH_SHORT).show();
            }
        }
        catch (Exception e)
        {
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void attachJavaToXML()
    {
        try
        {
            objectDialog =new Dialog(this);
            objectDialog.setContentView(R.layout.please_wait_dialog);

            objectToolbar=findViewById(R.id.allNotifications_tollbar);
            setSupportActionBar(objectToolbar);
            objectRecyclerView=findViewById(R.id.allNotifications_RecyclerView);

            objectToolbar.inflateMenu(R.menu.all_notifications_menu);

            objectToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    switch (item.getItemId())
                    {
                        case R.id.allNotifications_item_clear:
                            clearAllNotifications();
                            return true;
                        case R.id.allNotifications_item_goBack:
                            startActivity(new Intent(AllNotifications.this,MainContentPage.class));
                            return true;
                    }
                    return false;
                }
            });
        }
        catch (Exception e)
        {
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
}
zdwk9cvp

zdwk9cvp1#

问题是 menu 未连接到 AllNotifications .
要解决这个问题,你需要覆盖 onCreateOptionsMenu ```
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.my_menu, menu);
return super.onCreateOptionsMenu(menu);
}

替换 `my_menu` 菜单的名字在下面 `res/menu` 同时,要在菜单项上设置事件,您需要覆盖 `onOptionsItemSelected()` ```
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.allNotifications_item_clear) {
        // Do something

    } else if (id == R.id.allNotifications_item_goBack) {
        // Do something else 
    }

}

还有一点
看来你有个习惯 Toolbar 在布局中,因此可以使用

Toolbar toolbar = mView.findViewById(R.id.allNotifications_tollbar);
setSupportActionBar(toolbar);

但一定要使用 NoActionBar 主题。

相关问题