简体   繁体   中英

Change activity with action button click?

How can I change activities with my action button?

package com.com.com;

import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class HomeFragment extends Fragment {

public HomeFragment(){}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

//In order for this method to receive calls
setHasOptionsMenu(true);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

View rootView = inflater.inflate(R.layout.fragment_home, container, false);

return rootView;
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
  // Handle presses on the action bar items
  switch (item.getItemId()) {
      case R.id.action_new1:
          Button switchButton = (Button) findViewById(R.id.btnsignin);


          switchButton.setOnClickListener(new View.OnClickListener() {


          @Override

          public void onClick(View v) {

          Intent intent = new Intent(HomeFragment.this, Login.class);

          startActivity(intent);

          }

          });


          }   
          return true;
      default:
          return super.onOptionsItemSelected(item);
  }
}

This is my current code, but it doesn't seem to work. Can someone please explain how to get this working? I know that I need this

    @Override
public boolean onOptionsItemSelected(MenuItem item) {
  // Handle presses on the action bar items
  switch (item.getItemId()) {
      case R.id.action_new1:
          openSearch();
          return true;
      default:
          return super.onOptionsItemSelected(item);
  }

But I don't if I need to replace the openSearch with the code for a transition. Any help would be great.

Why you use that button there is it need!

That must work without any button like that:

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
  switch (item.getItemId()) {
      case R.id.action_new1:

          Intent intent = new Intent( getActivity(), Login.class);
          getActivity().startActivity(intent);

          return true;
      default:
          return super.onOptionsItemSelected(item);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM