即时通讯无法在搜索页上配置后退按钮,对我来说是Android的新手。
在mainactivity导航栏中单击,将打开searchpage活动。我想知道如何在搜索页操作栏上配置后退按钮,我使用onclick感到恐惧,但这似乎不起作用。这是主要的mainactivity和searchpage类。
谢谢。

java - 如何配置后退切换按钮?-LMLPHP

Mainactivity.class

public class MainActivity extends Login  {
public CardView cardView;
RecyclerView recyclerView;
DatabaseReference reference;
FirebaseRecyclerAdapter<Bookdeets, Bkhomeholder> adapter;
FirebaseRecyclerOptions<Bookdeets> options;
ProgressBar loading;
View header;
NavigationView navbar;
DrawerLayout drawerLayout;
ActionBarDrawerToggle mtoggle;
FirebaseAuth fAuth;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    cardView = (CardView) findViewById(R.id.bookcardview);
    reference = FirebaseDatabase.getInstance().getReference();
    reference.keepSynced(true);
    recyclerView = (RecyclerView) findViewById(R.id.rv);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
    loading = (ProgressBar) findViewById(R.id.loading);
    navbar = (NavigationView) findViewById(R.id.drawer);
    navbar.bringToFront();
    drawerLayout = (DrawerLayout) findViewById(R.id.drawerlay);
    header = navbar.getHeaderView(0);
    mtoggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowTitleEnabled(false);
    drawerLayout.addDrawerListener(mtoggle);
    mtoggle.syncState();
    fAuth= FirebaseAuth.getInstance();
    final String UserId = getIntent().getStringExtra("ID");
    options = new FirebaseRecyclerOptions.Builder<Bookdeets>()
            .setQuery(reference.child("BookDB"), Bookdeets.class).build();
    adapter = new FirebaseRecyclerAdapter<Bookdeets, Bkhomeholder>(options) {
        @Override
        protected void onBindViewHolder(@NonNull Bkhomeholder holder, final int position, @NonNull Bookdeets model) {

            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final String key = getRef(position).getKey().toString();
                    Intent i = new Intent(getApplicationContext(), Bookdetailslayouthome.class);
                    i.putExtra("key", key);
                    startActivity(i);
                }
            });
            Picasso.get().load(model.getImage()).into(holder.bookimg, new Callback() {
                @Override
                public void onSuccess() {
                    loading.setVisibility(View.GONE);
                }

                @Override
                public void onError(Exception e) {
                    Toast.makeText(getApplicationContext(), "could not get the image", Toast.LENGTH_LONG).show();
                    loading.setVisibility(View.GONE);
                }
            });
            holder.title.setText(model.getBookname());
        }

        @NonNull
        @Override
        public Bkhomeholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardviewlay, parent, false);
            return new Bkhomeholder(view);
        }
    };
    GridLayoutManager gridLayoutManager = new GridLayoutManager(getApplicationContext(), 3);
    recyclerView.setLayoutManager(gridLayoutManager);
    adapter.startListening();
    recyclerView.setAdapter(adapter);
    navbar.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            int id = item.getItemId();
            drawerLayout.closeDrawers();

            if(id== R.id.home) {

                drawerLayout.closeDrawer(GravityCompat.START);
            }
            else if(id== R.id.browse) {
                Toast.makeText(getApplicationContext(),"hello",Toast.LENGTH_LONG).show();
            }
            else if(id== R.id.search) {

                 Intent search = new Intent(getApplicationContext(), SearchPage.class);
            startActivity(search);
            }
            else if(id== R.id.Profile) {
                Intent sendtopro=new Intent(getApplicationContext(), Profile.class);
                sendtopro.putExtra("Ukey",UserId);
                startActivity(sendtopro);
            }
            else if(id== R.id.addbkbtn) {

                Intent adbk = new Intent(getApplicationContext(), Addbooks.class);
                adbk.putExtra("UID","User");
                startActivity(adbk);
            }
            else if(id== R.id.Logoutbtn) {
                fAuth.signOut();
                Intent intent = new Intent(getApplicationContext(), Login.class);
                startActivity(intent);
                finish();
            }
            drawerLayout.closeDrawer(GravityCompat.START);
            return true;
        }
    });
}

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    if (mtoggle.onOptionsItemSelected(item)) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

@Override
public void onBackPressed() {
    if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
        drawerLayout.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}
@Override
protected void onStart() {
    super.onStart();
    if (adapter != null)
        adapter.startListening();
    loading.setVisibility(View.VISIBLE);
}
@Override
protected void onStop() {
    super.onStop();
    if (adapter != null)
        adapter.stopListening();
}
@Override
protected void onResume() {
    super.onResume();
    if (adapter != null)
        adapter.startListening();
}


Searchpage.class

public class SearchPage extends AppCompatActivity {
EditText searchbar;
RecyclerView recyclerView;
DatabaseReference reference;
ArrayList<String> BookNameList;
ArrayList<String> AuthorNameList;
ArrayList<String> PicList;
ArrayList<String> PublisherList;
ArrayList<String> LinkList;
ArrayList<String> DescriptionList;
FirebaseAnalytics mFirebaseAnalytics;
ActionBarDrawerToggle mtoggle;
DrawerLayout drawerLayout;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_search_page);
    searchbar = (EditText) findViewById(R.id.searchbar);
    reference = FirebaseDatabase.getInstance().getReference();
    reference.keepSynced(true);
    recyclerView = (RecyclerView) findViewById(R.id.rv);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
    mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
    mtoggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    BookNameList = new ArrayList<>();
    PublisherList = new ArrayList<>();
    AuthorNameList = new ArrayList<>();
    LinkList = new ArrayList<>();
    PicList = new ArrayList<>();
    DescriptionList=new ArrayList<>();
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowTitleEnabled(false);
    searchbar.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
        @Override
        public void afterTextChanged(Editable s) {
            if (!s.toString().isEmpty()) {
                setAdapter(s.toString());
            }
            else{
                BookNameList.clear();
                AuthorNameList.clear();
                PicList.clear();
                PublisherList.clear();
                DescriptionList.clear();

            }
        }

        private void setAdapter(final String searchedString) {
            reference.child("BookDB").addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    BookNameList.clear();
                    AuthorNameList.clear();
                    PicList.clear();
                    PublisherList.clear();
                    DescriptionList.clear();

                    int counter=0;
                    for(DataSnapshot snapshot:dataSnapshot.getChildren()){
                        String uid = snapshot.getKey();
                        String desc = snapshot.child("Desc").getValue(String.class);
                        String bookname = snapshot.child("bookname").getValue(String.class);
                        String author = snapshot.child("author").getValue(String.class);
                        String image = snapshot.child("image").getValue(String.class);
                        String publisher = snapshot.child("Publisher").getValue(String.class);


                        try {

                            if ((bookname.toLowerCase().contains(searchedString.toLowerCase())) || (author.toLowerCase().contains(searchedString.toLowerCase()))) {
                                BookNameList.add(bookname);
                                AuthorNameList.add(author);
                                PublisherList.add(publisher);
                                PicList.add(image);

                                counter++;
                            }
                            if(BookNameList.isEmpty() && AuthorNameList.isEmpty())
                            {

                            }
                        }
                        catch (Exception e){
                        }
                        if(counter==15){
                            break;
                        }
                        SearchAdapter searchAdapter = new SearchAdapter(SearchPage.this, BookNameList, AuthorNameList, PicList, PublisherList,DescriptionList,LinkList);
                        recyclerView.setAdapter(searchAdapter);
                    }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {
                }
            });
        }
    });    }

@Override
public void onBackPressed() {
    Intent gob=new Intent(getApplicationContext(),MainActivity.class);
    startActivity(gob);
}

最佳答案

在您的Searchpage活动中更改此内容

@Override
public void onBackPressed() {
    Intent gob=new Intent(getApplicationContext(),MainActivity.class);
    startActivity(gob);
}




@Override
public void onBackPressed() {
    super.onBackPressed();
}

09-30 21:28