Linking Button to an existing activity in android

时间:2017-12-18 06:01:53

标签: android android-activity menu

I have an activity that has already been crated for nav drawer. I would like to connect a button for search in for quick navigation in that I don't need to open the drawer for search here is my code as follow:

main.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/nav_search"
        android:icon="@drawable/ic_search"
        android:title="@string/search"
        app:showAsAction="always" />

</menu> 

Am main activity is as follow.

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    Fragment currFragment;
    boolean isLoggedPrev, isLoggedCurrent;
    NavigationView navigationView;
    boolean doubleBackToExitPressedOnce = false;
    public static int offsetY = 0;
    private AdView adView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {

            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
            }

            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                if (UserAccessSession.getInstance(MainActivity.this).getUserSession() != null) {
                    isLoggedCurrent = true;
                } else {
                    isLoggedCurrent = false;
                }

                if (isLoggedCurrent != isLoggedPrev) {
                    isLoggedPrev = isLoggedCurrent;
                    checkLoginNavigation();
                }
            }
        };

        drawer.setDrawerListener(toggle);
        toggle.syncState();

        TypedValue tv = new TypedValue();
        if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
            offsetY = TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics());
            Config.OFFSET_Y = offsetY;
        }
        showFragment(new HomeFragment());
        showAds();
    }

    public void checkLoginNavigation() {
        navigationView.getMenu().clear();
        UserSession userSession = UserAccessSession.getInstance(this).getUserSession();
        if (userSession != null) {
            navigationView.inflateMenu(R.menu.activity_main_drawer_logged);
        } else {
            navigationView.inflateMenu(R.menu.activity_main_drawer_not_logged);
        }
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            if (doubleBackToExitPressedOnce) {
                super.onBackPressed();
                return;
            }
            doubleBackToExitPressedOnce = true;
            Toast.makeText(this, R.string.tap_back_again_to_exit, Toast.LENGTH_SHORT).show();
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    doubleBackToExitPressedOnce = false;
                }
            }, 2000);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        Intent i;
        int id = item.getItemId();
        if(id == R.id.nav_home) {
            showFragment(new HomeFragment());
            setTitle(R.string.app_name);
        }
        if(id == R.id.nav_categories) {
            showFragment(new CategoryFragment());
            setTitle(R.string.categories);
        }
        if(id == R.id.nav_favorites) {
            showFragment(new FavoritesFragment());
            setTitle(R.string.favorites);
        }
        if(id == R.id.nav_featured) {
            showFragment(new FeaturedFragment());
            setTitle(R.string.featured);
        }
        if(id == R.id.nav_search) {
            i = new Intent(this, SearchActivity.class);
            startActivity(i);
        }
        if(id == R.id.nav_news) {
            showFragment(new NewsFragment());
            setTitle(R.string.latest_news);
        }
        if(id == R.id.nav_about_us) {
            showFragment(new AboutUsFragment());
            setTitle(R.string.about_us);
        }
        if(id == R.id.nav_terms_condition) {
            showFragment(new TermsConditionFragment());
            setTitle(R.string.terms_and_conditions);
        }
        if(id == R.id.nav_settings) {
            i = new Intent(this, SettingsActivity.class);
            startActivity(i);
        }
        if(id == R.id.nav_login) {
            i = new Intent(this, LoginActivity.class);
            startActivity(i);
        }
        if(id == R.id.nav_profile) {
            i = new Intent(this, ProfileActivity.class);
            startActivity(i);
        }
        if(id == R.id.nav_my_events) {
            i = new Intent(this, MyEventsActivity.class);
            startActivity(i);
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    public void showFragment(Fragment fragment) {
        if (currFragment != null && fragment.getClass().equals(currFragment.getClass()))
            return;

        currFragment = fragment;
        FragmentManager fragmentManager = this.getSupportFragmentManager();
        if (fragmentManager == null)
            return;

        FragmentTransaction ft = fragmentManager.beginTransaction();
        if (ft == null)
            return;

        ft.replace(R.id.content_frame, fragment).commitAllowingStateLoss();
    }

I would love when I click the search button it loads the activity for search, which is currently being used by navigation drawer.

2 个答案:

答案 0 :(得分:0)

FYI

android:id="@+id/nav_search" is MenuItem not part of NavigationItem remove it from your onNavigationItemSelected() and add in to onOptionsItemSelected()

Try this

@Override
public boolean onOptionsItemSelected(MenuItem item) {
   int id = item.getItemId();
   if(id == R.id.nav_search) {
       i = new Intent(this, SearchActivity.class);
       startActivity(i);
       return true;
   }

   return super.onOptionsItemSelected(item);
}

答案 1 :(得分:0)

Its the MenuItem not NavigationItem.

  @Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.nav_search) {
        // do your stuff here
    }
    return super.onOptionsItemSelected(item);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.yourMenu,menu);
    return super.onCreateOptionsMenu(menu);
}